This repository has been archived on 2025-12-11. You can view files and clone it, but cannot push or open issues or pull requests.

412 lines
6.3 MiB
JavaScript
Raw Normal View History

2025-03-17 13:54:06 +01:00
/*!
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
* _ _ _ _
* | |___ __ / \ __| |_ __ ___ (_)_ __
* | __\ \/ / / _ \ / _` | '_ ` _ \| | '_ \
* | |_ > < / ___ \ (_| | | | | | | | | | |
* \__/_/\_\/_/ \_\__,_|_| |_| |_|_|_| |_|
*
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
* Author: André Tabarra (https://github.com/tabarra)
* Repository: https://github.com/tabarra/txAdmin
* txAdmin is a free open source software provided under the license below.
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
* MIT License
*
* Copyright (c) 2019-2025 André Tabarra <maintainer@txadmin.gg>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
* This distribution also includes third party code under their own licenses, which
* can be found in ../THIRD-PARTY-LICENSES.txt or their respective repositories.
* Attribution for non-code assets can be found at the bottom of ../README.md or at
* the top of the respective file.
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*/
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __typeError=msg=>{throw TypeError(msg)};var __esm=(fn2,res)=>function __init(){return fn2&&(res=(0,fn2[__getOwnPropNames(fn2)[0]])(fn2=0)),res};var __commonJS=(cb,mod3)=>function __require(){return mod3||(0,cb[__getOwnPropNames(cb)[0]])((mod3={exports:{}}).exports,mod3),mod3.exports};var __export=(target,all2)=>{for(var name in all2)__defProp(target,name,{get:all2[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod3,isNodeMode,target)=>(target=mod3!=null?__create(__getProtoOf(mod3)):{},__copyProps(isNodeMode||!mod3||!mod3.__esModule?__defProp(target,"default",{value:mod3,enumerable:true}):target,mod3));var __toCommonJS=mod3=>__copyProps(__defProp({},"__esModule",{value:true}),mod3);var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj));var __privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value);var __privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value);var require_stackframe=__commonJS({"node_modules/stackframe/stackframe.js"(exports2,module2){(function(root2,factory){"use strict";if(typeof define==="function"&&define.amd){define("stackframe",[],factory)}else if(typeof exports2==="object"){module2.exports=factory()}else{root2.StackFrame=factory()}})(exports2,function(){"use strict";function _isNumber(n){return!isNaN(parseFloat(n))&&isFinite(n)}function _capitalize(str2){return str2.charAt(0).toUpperCase()+str2.substring(1)}function _getter(p){return function(){return this[p]}}var booleanProps=["isConstructor","isEval","isNative","isToplevel"];var numericProps=["columnNumber","lineNumber"];var stringProps=["fileName","functionName","source"];var arrayProps=["args"];var objectProps=["evalOrigin"];var props=booleanProps.concat(numericProps,stringProps,arrayProps,objectProps);function StackFrame(obj){if(!obj)return;for(var i2=0;i2<props.length;i2++){if(obj[props[i2]]!==void 0){this["set"+_capitalize(props[i2])](obj[props[i2]])}}}StackFrame.prototype={getArgs:function(){return this.args},setArgs:function(v){if(Object.prototype.toString.call(v)!=="[object Array]"){throw new TypeError("Args must be an Array")}this.args=v},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(v){if(v instanceof StackFrame){this.evalOrigin=v}else if(v instanceof Object){this.evalOrigin=new StackFrame(v)}else{throw new TypeError("Eval Origin must be an Object or StackFrame")}},toString:function(){var fileName=this.getFileName()||"";var lineNumber=this.getLineNumber()||"";var columnNumber=this.getColumnNumber()||"";var functionName=this.getFunctionName()||"";if(this.getIsEval()){if(fileName){return"[eval] ("+fileName+":"+lineNumber+":"+columnNumber+")"}return"[eval]:"+lineNumber+":"+columnNumber}if(functionName){return functionName+" ("+fileName+":"+lineNumber+":"+columnNumber+")"}return fileName+":"+lineNumber+":"+columnNumber}};StackFrame.fromString=function StackFrame$$fromString(str2){var argsStartIndex=str2.indexOf("(");var argsEndIndex=str2.lastIndexOf(")");var functionName=str2.substring(0,argsStartIndex);var args2=str2.substring(argsStartIndex+1,argsEndIndex).split(",");var locationString=str2.substring(argsEndIndex+1);if(locationString.indexOf("@")===0){var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationSt
${error.message}`:execaMessage;const message3=[shortMessage,stderr,stdout].filter(Boolean).join("\n");if(isError2){error.originalMessage=error.message;error.message=message3}else{error=new Error(message3)}error.shortMessage=shortMessage;error.command=command;error.escapedCommand=escapedCommand;error.exitCode=exitCode;error.signal=signal;error.signalDescription=signalDescription;error.stdout=stdout;error.stderr=stderr;if(all2!==void 0){error.all=all2}if("bufferedData"in error){delete error.bufferedData}error.failed=true;error.timedOut=Boolean(timedOut2);error.isCanceled=isCanceled;error.killed=killed&&!timedOut2;return error};module2.exports=makeError}});var require_stdio=__commonJS({"node_modules/execa/lib/stdio.js"(exports2,module2){"use strict";var aliases2=["stdin","stdout","stderr"];var hasAlias=options=>aliases2.some(alias=>options[alias]!==void 0);var normalizeStdio=options=>{if(!options){return}const{stdio}=options;if(stdio===void 0){return aliases2.map(alias=>options[alias])}if(hasAlias(options)){throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases2.map(alias=>`\`${alias}\``).join(", ")}`)}if(typeof stdio==="string"){return stdio}if(!Array.isArray(stdio)){throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``)}const length=Math.max(stdio.length,aliases2.length);return Array.from({length},(value,index)=>stdio[index])};module2.exports=normalizeStdio;module2.exports.node=options=>{const stdio=normalizeStdio(options);if(stdio==="ipc"){return"ipc"}if(stdio===void 0||typeof stdio==="string"){return[stdio,stdio,stdio,"ipc"]}if(stdio.includes("ipc")){return stdio}return[...stdio,"ipc"]}}});var require_signals2=__commonJS({"node_modules/execa/node_modules/signal-exit/signals.js"(exports2,module2){module2.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){module2.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){module2.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}}});var require_signal_exit=__commonJS({"node_modules/execa/node_modules/signal-exit/index.js"(exports2,module2){var process6=global.process;var processOk=function(process7){return process7&&typeof process7==="object"&&typeof process7.removeListener==="function"&&typeof process7.emit==="function"&&typeof process7.reallyExit==="function"&&typeof process7.listeners==="function"&&typeof process7.kill==="function"&&typeof process7.pid==="number"&&typeof process7.on==="function"};if(!processOk(process6)){module2.exports=function(){return function(){}}}else{assert2=require("assert");signals=require_signals2();isWin=/^win/i.test(process6.platform);EE=require("events");if(typeof EE!=="function"){EE=EE.EventEmitter}if(process6.__signal_exit_emitter__){emitter=process6.__signal_exit_emitter__}else{emitter=process6.__signal_exit_emitter__=new EE;emitter.count=0;emitter.emitted={}}if(!emitter.infinite){emitter.setMaxListeners(Infinity);emitter.infinite=true}module2.exports=function(cb,opts){if(!processOk(global.process)){return function(){}}assert2.equal(typeof cb,"function","a callback must be provided for exit handler");if(loaded===false){load2()}var ev="exit";if(opts&&opts.alwaysLast){ev="afterexit"}var remove2=function(){emitter.removeListener(ev,cb);if(emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0){unload()}};emitter.on(ev,cb);return remove2};unload=function unload2(){if(!loaded||!processOk(global.process)){return}loaded=false;signals.forEach(function(sig){try{process6.removeListener(sig,sigListeners[sig])}catch(er){}});process6.emit=originalProcessEmit;process6.reallyExit=originalProcessReallyExit;emitter.count-=1};module2.exports.unload=unload;emit=function emit2(event,code,signal){if(emitter.emitted[event]){return}emitter.emitted[event]=true;emitter.emit(event,code,signal)};sigListeners={};signals.forEach(function(sig){sigListeners[sig]=function listener(){if(!processOk(global.process)){return}var listeners=process
echo -n "product_serial: "; cat /sys/devices/virtual/dmi/id/product_serial 2>/dev/null; echo;
echo -n "product_uuid: "; cat /sys/devices/virtual/dmi/id/product_uuid 2>/dev/null; echo;
echo -n "product_version: "; cat /sys/devices/virtual/dmi/id/product_version 2>/dev/null; echo;
echo -n "sys_vendor: "; cat /sys/devices/virtual/dmi/id/sys_vendor 2>/dev/null; echo;`;try{lines=execSync(cmd,util4.execOptsLinux).toString().split("\n");result2.manufacturer=cleanDefaults(result2.manufacturer===""?util4.getValue(lines,"sys_vendor"):result2.manufacturer);result2.model=cleanDefaults(result2.model===""?util4.getValue(lines,"product_name"):result2.model);result2.version=cleanDefaults(result2.version===""?util4.getValue(lines,"product_version"):result2.version);result2.serial=cleanDefaults(result2.serial===""?util4.getValue(lines,"product_serial"):result2.serial);result2.uuid=cleanDefaults(result2.uuid===""?util4.getValue(lines,"product_uuid").toLowerCase():result2.uuid)}catch(e){util4.noop()}if(!result2.serial){result2.serial="-"}if(!result2.manufacturer){result2.manufacturer=""}if(!result2.model){result2.model="Computer"}if(!result2.version){result2.version=""}if(!result2.sku){result2.sku="-"}if(result2.model.toLowerCase()==="virtualbox"||result2.model.toLowerCase()==="kvm"||result2.model.toLowerCase()==="virtual machine"||result2.model.toLowerCase()==="bochs"||result2.model.toLowerCase().startsWith("vmware")||result2.model.toLowerCase().startsWith("droplet")){result2.virtual=true;switch(result2.model.toLowerCase()){case"virtualbox":result2.virtualHost="VirtualBox";break;case"vmware":result2.virtualHost="VMware";break;case"kvm":result2.virtualHost="KVM";break;case"bochs":result2.virtualHost="bochs";break}}if(result2.manufacturer.toLowerCase().startsWith("vmware")||result2.manufacturer.toLowerCase()==="xen"){result2.virtual=true;switch(result2.manufacturer.toLowerCase()){case"vmware":result2.virtualHost="VMware";break;case"xen":result2.virtualHost="Xen";break}}if(!result2.virtual){try{const disksById=execSync("ls -1 /dev/disk/by-id/ 2>/dev/null",util4.execOptsLinux).toString();if(disksById.indexOf("_QEMU_")>=0){result2.virtual=true;result2.virtualHost="QEMU"}if(disksById.indexOf("_VBOX_")>=0){result2.virtual=true;result2.virtualHost="VirtualBox"}}catch(e){util4.noop()}}if(!result2.virtual&&(os7.release().toLowerCase().indexOf("microsoft")>=0||os7.release().toLowerCase().endsWith("wsl2"))){const kernelVersion=parseFloat(os7.release().toLowerCase());result2.virtual=true;result2.manufacturer="Microsoft";result2.model="WSL";result2.version=kernelVersion<4.19?"1":"2"}if((_freebsd||_openbsd||_netbsd)&&!result2.virtualHost){try{const procInfo=execSync("dmidecode -t 4",util4.execOptsLinux);const procLines=procInfo.toString().split("\n");const procManufacturer=util4.getValue(procLines,"manufacturer",":",true);switch(procManufacturer.toLowerCase()){case"virtualbox":result2.virtualHost="VirtualBox";break;case"vmware":result2.virtualHost="VMware";break;case"kvm":result2.virtualHost="KVM";break;case"bochs":result2.virtualHost="bochs";break}}catch(e){util4.noop()}}if(fs13.existsSync("/.dockerenv")||fs13.existsSync("/.dockerinit")){result2.model="Docker Container"}try{const stdout2=execSync('dmesg 2>/dev/null | grep -iE "virtual|hypervisor" | grep -iE "vmware|qemu|kvm|xen" | grep -viE "Nested Virtualization|/virtual/"');let lines2=stdout2.toString().split("\n");if(lines2.length>0){if(result2.model==="Computer"){result2.model="Virtual machine"}result2.virtual=true;if(stdout2.toString().toLowerCase().indexOf("vmware")>=0&&!result2.virtualHost){result2.virtualHost="VMware"}if(stdout2.toString().toLowerCase().indexOf("qemu")>=0&&!result2.virtualHost){result2.virtualHost="QEMU"}if(stdout2.toString().toLowerCase().indexOf("xen")>=0&&!result2.virtualHost){result2.virtualHost="Xen"}if(stdout2.toString().toLowerCase().indexOf("kvm")>=0&&!result2.virtualHost){result2.virtualHost="KVM"}}}catch(e){util4.noop()}if(result2.manufacturer===""&&result2.model==="Computer"&&result2.version===""){fs13.readFile("/proc/cpuinfo",function(error2,stdout2){if(!error2){let lines2=stdout2.toString().split("\n");result2.model=util4.getValue(lines2,"hardware",":",true).toUpperCase();result2.version=util4.getValue(lines2,"revision",":",true).toLowerCase();result2.serial=util4.getValue(lines2,"serial",":",true);const model=util4.getValue(li
echo -n "bios_vendor: "; cat /sys/devices/virtual/dmi/id/bios_vendor 2>/dev/null; echo;
echo -n "bios_version: "; cat /sys/devices/virtual/dmi/id/bios_version 2>/dev/null; echo;`;try{lines=execSync(cmd2,util4.execOptsLinux).toString().split("\n");result2.vendor=!result2.vendor?util4.getValue(lines,"bios_vendor"):result2.vendor;result2.version=!result2.version?util4.getValue(lines,"bios_version"):result2.version;datetime=util4.getValue(lines,"bios_date");result2.releaseDate=!result2.releaseDate?util4.parseDateTime(datetime).date:result2.releaseDate}catch(e){util4.noop()}if(callback){callback(result2)}resolve(result2)})}if(_darwin){result2.vendor="Apple Inc.";exec3("system_profiler SPHardwareDataType -json",function(error,stdout){try{const hardwareData=JSON.parse(stdout.toString());if(hardwareData&&hardwareData.SPHardwareDataType&&hardwareData.SPHardwareDataType.length){let bootRomVersion=hardwareData.SPHardwareDataType[0].boot_rom_version;bootRomVersion=bootRomVersion?bootRomVersion.split("(")[0].trim():null;result2.version=bootRomVersion}}catch(e){util4.noop()}if(callback){callback(result2)}resolve(result2)})}if(_sunos){result2.vendor="Sun Microsystems";if(callback){callback(result2)}resolve(result2)}if(_windows){try{util4.powerShell('Get-CimInstance Win32_bios | select Description,Version,Manufacturer,@{n="ReleaseDate";e={$_.ReleaseDate.ToString("yyyy-MM-dd")}},BuildNumber,SerialNumber,SMBIOSBIOSVersion | fl').then((stdout,error)=>{if(!error){let lines=stdout.toString().split("\r\n");const description=util4.getValue(lines,"description",":");const version=util4.getValue(lines,"SMBIOSBIOSVersion",":");if(description.indexOf(" Version ")!==-1){result2.vendor=description.split(" Version ")[0].trim();result2.version=description.split(" Version ")[1].trim()}else if(description.indexOf(" Ver: ")!==-1){result2.vendor=util4.getValue(lines,"manufacturer",":");result2.version=description.split(" Ver: ")[1].trim()}else{result2.vendor=util4.getValue(lines,"manufacturer",":");result2.version=version||util4.getValue(lines,"version",":")}result2.releaseDate=util4.getValue(lines,"releasedate",":");result2.revision=util4.getValue(lines,"buildnumber",":");result2.serial=cleanDefaults(util4.getValue(lines,"serialnumber",":"))}if(callback){callback(result2)}resolve(result2)})}catch(e){if(callback){callback(result2)}resolve(result2)}}})})}exports2.bios=bios;function baseboard(callback){return new Promise(resolve=>{process.nextTick(()=>{let result2={manufacturer:"",model:"",version:"",serial:"-",assetTag:"-",memMax:null,memSlots:null};let cmd="";if(_linux||_freebsd||_openbsd||_netbsd){if(process.arch==="arm"){cmd="cat /proc/cpuinfo | grep Serial"}else{cmd="export LC_ALL=C; dmidecode -t 2 2>/dev/null; unset LC_ALL"}const workload=[];workload.push(execPromise(cmd));workload.push(execPromise("export LC_ALL=C; dmidecode -t memory 2>/dev/null"));util4.promiseAll(workload).then(data=>{let lines=data.results[0]?data.results[0].toString().split("\n"):[""];result2.manufacturer=cleanDefaults(util4.getValue(lines,"Manufacturer"));result2.model=cleanDefaults(util4.getValue(lines,"Product Name"));result2.version=cleanDefaults(util4.getValue(lines,"Version"));result2.serial=cleanDefaults(util4.getValue(lines,"Serial Number"));result2.assetTag=cleanDefaults(util4.getValue(lines,"Asset Tag"));const cmd2=`echo -n "board_asset_tag: "; cat /sys/devices/virtual/dmi/id/board_asset_tag 2>/dev/null; echo;
echo -n "board_name: "; cat /sys/devices/virtual/dmi/id/board_name 2>/dev/null; echo;
echo -n "board_serial: "; cat /sys/devices/virtual/dmi/id/board_serial 2>/dev/null; echo;
echo -n "board_vendor: "; cat /sys/devices/virtual/dmi/id/board_vendor 2>/dev/null; echo;
echo -n "board_version: "; cat /sys/devices/virtual/dmi/id/board_version 2>/dev/null; echo;`;try{lines=execSync(cmd2,util4.execOptsLinux).toString().split("\n");result2.manufacturer=cleanDefaults(!result2.manufacturer?util4.getValue(lines,"board_vendor"):result2.manufacturer);result2.model=cleanDefaults(!result2.model?util4.getValue(lines,"board_name"):result2.model);result2.version=cleanDefaults(!result2.version?util4.getValue(lines,"board_version"):result2.version);result2.serial=cleanDefaults(!result2.serial?util4.getValue(lines,"board_serial"):result2.serial);result2.assetTag=cleanDefaults(!result2.assetTag?util4.getValue(lines,"board_asset_tag"):result2.assetTag)}catch(e){util4.noop()}lines=data.results[1]?data.results[1].toString().split("\n"):[""];result2.memMax=util4.toInt(util4.getValue(lines,"Maximum Capacity"))*1024*1024*1024||null;result2.memSlots=util4.toInt(util4.getValue(lines,"Number Of Devices"))||null;let linesRpi="";try{linesRpi=fs13.readFileSync("/proc/cpuinfo").toString().split("\n")}catch(e){util4.noop()}if(linesRpi){const hardware=util4.getValue(linesRpi,"hardware");if(hardware.startsWith("BCM")){const rpi=util4.decodePiCpuinfo(linesRpi);result2.manufacturer=rpi.manufacturer;result2.model="Raspberry Pi";result2.serial=rpi.serial;result2.version=rpi.type+" - "+rpi.revision;result2.memMax=os7.totalmem();result2.memSlots=0}}if(callback){callback(result2)}resolve(result2)})}if(_darwin){const workload=[];workload.push(execPromise("ioreg -c IOPlatformExpertDevice -d 2"));workload.push(execPromise("system_profiler SPMemoryDataType"));util4.promiseAll(workload).then(data=>{let lines=data.results[0]?data.results[0].toString().replace(/[<>"]/g,"").split("\n"):[""];result2.manufacturer=util4.getValue(lines,"manufacturer","=",true);result2.model=util4.getValue(lines,"model","=",true);result2.version=util4.getValue(lines,"version","=",true);result2.serial=util4.getValue(lines,"ioplatformserialnumber","=",true);result2.assetTag=util4.getValue(lines,"board-id","=",true);let devices=data.results[1]?data.results[1].toString().split(" BANK "):[""];if(devices.length===1){devices=data.results[1]?data.results[1].toString().split(" DIMM"):[""]}devices.shift();result2.memSlots=devices.length;if(os7.arch()==="arm64"){result2.memSlots=0;result2.memMax=os7.totalmem()}if(callback){callback(result2)}resolve(result2)})}if(_sunos){if(callback){callback(result2)}resolve(result2)}if(_windows){try{const workload=[];const win10plus=parseInt(os7.release())>=10;const maxCapacityAttribute=win10plus?"MaxCapacityEx":"MaxCapacity";workload.push(util4.powerShell("Get-CimInstance Win32_baseboard | select Model,Manufacturer,Product,Version,SerialNumber,PartNumber,SKU | fl"));workload.push(util4.powerShell(`Get-CimInstance Win32_physicalmemoryarray | select ${maxCapacityAttribute}, MemoryDevices | fl`));util4.promiseAll(workload).then(data=>{let lines=data.results[0]?data.results[0].toString().split("\r\n"):[""];result2.manufacturer=cleanDefaults(util4.getValue(lines,"manufacturer",":"));result2.model=cleanDefaults(util4.getValue(lines,"model",":"));if(!result2.model){result2.model=cleanDefaults(util4.getValue(lines,"product",":"))}result2.version=cleanDefaults(util4.getValue(lines,"version",":"));result2.serial=cleanDefaults(util4.getValue(lines,"serialnumber",":"));result2.assetTag=cleanDefaults(util4.getValue(lines,"partnumber",":"));if(!result2.assetTag){result2.assetTag=cleanDefaults(util4.getValue(lines,"sku",":"))}lines=data.results[1]?data.results[1].toString().split("\r\n"):[""];result2.memMax=util4.toInt(util4.getValue(lines,maxCapacityAttribute,":"))*(win10plus?1024:1)||null;result2.memSlots=util4.toInt(util4.getValue(lines,"MemoryDevices",":"))||null;if(callback){callback(result2)}resolve(result2)})}catch(e){if(callback){callback(result2)}resolve(result2)}}})})}exports2.baseboard=baseboard;function macOsChassisType(model){model=model.toLowerCase();if(model.indexOf("macbookair")>=0||model.indexOf("macbook air")>=0){return"Notebook"}if(model.indexOf("macbookpro")>=0||model.indexOf("macbook pro")>=0){retur
echo -n "chassis_serial: "; cat /sys/devices/virtual/dmi/id/chassis_serial 2>/dev/null; echo;
echo -n "chassis_type: "; cat /sys/devices/virtual/dmi/id/chassis_type 2>/dev/null; echo;
echo -n "chassis_vendor: "; cat /sys/devices/virtual/dmi/id/chassis_vendor 2>/dev/null; echo;
echo -n "chassis_version: "; cat /sys/devices/virtual/dmi/id/chassis_version 2>/dev/null; echo;`;exec3(cmd,function(error,stdout){let lines=stdout.toString().split("\n");result2.manufacturer=cleanDefaults(util4.getValue(lines,"chassis_vendor"));const ctype=parseInt(util4.getValue(lines,"chassis_type").replace(/\D/g,""));result2.type=cleanDefaults(ctype&&!isNaN(ctype)&&ctype<chassisTypes.length?chassisTypes[ctype-1]:"");result2.version=cleanDefaults(util4.getValue(lines,"chassis_version"));result2.serial=cleanDefaults(util4.getValue(lines,"chassis_serial"));result2.assetTag=cleanDefaults(util4.getValue(lines,"chassis_asset_tag"));if(callback){callback(result2)}resolve(result2)})}if(_darwin){exec3("ioreg -c IOPlatformExpertDevice -d 2",function(error,stdout){if(!error){let lines=stdout.toString().replace(/[<>"]/g,"").split("\n");const model=util4.getAppleModel(util4.getValue(lines,"model","=",true));result2.manufacturer=util4.getValue(lines,"manufacturer","=",true);result2.model=model.key;result2.type=macOsChassisType(model.model);result2.version=model.version;result2.serial=util4.getValue(lines,"ioplatformserialnumber","=",true);result2.assetTag=util4.getValue(lines,"board-id","=",true)||util4.getValue(lines,"target-type","=",true);result2.sku=util4.getValue(lines,"target-sub-type","=",true)}if(callback){callback(result2)}resolve(result2)})}if(_sunos){if(callback){callback(result2)}resolve(result2)}if(_windows){try{util4.powerShell("Get-CimInstance Win32_SystemEnclosure | select Model,Manufacturer,ChassisTypes,Version,SerialNumber,PartNumber,SKU,SMBIOSAssetTag | fl").then((stdout,error)=>{if(!error){let lines=stdout.toString().split("\r\n");result2.manufacturer=cleanDefaults(util4.getValue(lines,"manufacturer",":"));result2.model=cleanDefaults(util4.getValue(lines,"model",":"));const ctype=parseInt(util4.getValue(lines,"ChassisTypes",":").replace(/\D/g,""));result2.type=ctype&&!isNaN(ctype)&&ctype<chassisTypes.length?chassisTypes[ctype-1]:"";result2.version=cleanDefaults(util4.getValue(lines,"version",":"));result2.serial=cleanDefaults(util4.getValue(lines,"serialnumber",":"));result2.assetTag=cleanDefaults(util4.getValue(lines,"partnumber",":"));if(!result2.assetTag){result2.assetTag=cleanDefaults(util4.getValue(lines,"SMBIOSAssetTag",":"))}result2.sku=cleanDefaults(util4.getValue(lines,"sku",":"))}if(callback){callback(result2)}resolve(result2)})}catch(e){if(callback){callback(result2)}resolve(result2)}}})})}exports2.chassis=chassis}});var require_osinfo=__commonJS({"node_modules/systeminformation/lib/osinfo.js"(exports2){"use strict";var os7=require("os");var fs13=require("fs");var util4=require_util2();var exec3=require("child_process").exec;var execSync=require("child_process").execSync;var _platform=process.platform;var _linux=_platform==="linux"||_platform==="android";var _darwin=_platform==="darwin";var _windows=_platform==="win32";var _freebsd=_platform==="freebsd";var _openbsd=_platform==="openbsd";var _netbsd=_platform==="netbsd";var _sunos=_platform==="sunos";function time(){let t=new Date().toString().split(" ");const result2={current:Date.now(),uptime:os7.uptime(),timezone:t.length>=7?t[5]:"",timezoneName:Intl?Intl.DateTimeFormat().resolvedOptions().timeZone:t.length>=7?t.slice(6).join(" ").replace(/\(/g,"").replace(/\)/g,""):""};if(_darwin||_linux){try{const stdout=execSync("date +%Z && date +%z && ls -l /etc/localtime 2>/dev/null",util4.execOptsLinux);const lines=stdout.toString().split(os7.EOL);if(lines.length>3&&!lines[0]){lines.shift()}let timezone2=lines[0]||"";if(timezone2.startsWith("+")||timezone2.startsWith("-")){timezone2="GMT"}return{current:Date.now(),uptime:os7.uptime(),timezone:lines[1]?timezone2+lines[1]:timezone2,timezoneName:lines[2]&&lines[2].indexOf("/zoneinfo/")>0?lines[2].split("/zoneinfo/")[1]||"":""}}catch(e){util4.noop()}}return result2}exports2.time=time;function getLogoFile(distro){distro=distro||"";distro=distro.toLowerCase();let result2=_platform;if(_windows){result2="windows"}else if(distro.indexOf("mac os")!==-1||distro.indexOf("macos")!==-1){result2="apple"}else i
cat /etc/machine-id 2> /dev/null; echo;
echo -n "hardware: "; cat /sys/class/dmi/id/product_uuid 2> /dev/null; echo;`;exec3(cmd,function(error,stdout){const lines=stdout.toString().split("\n");result2.os=util4.getValue(lines,"os").toLowerCase();result2.hardware=util4.getValue(lines,"hardware").toLowerCase();if(!result2.hardware){const lines2=fs13.readFileSync("/proc/cpuinfo",{encoding:"utf8"}).toString().split("\n");const serial=util4.getValue(lines2,"serial");result2.hardware=serial||""}if(callback){callback(result2)}resolve(result2)})}if(_freebsd||_openbsd||_netbsd){exec3("sysctl -i kern.hostid kern.hostuuid",function(error,stdout){const lines=stdout.toString().split("\n");result2.os=util4.getValue(lines,"kern.hostid",":").toLowerCase();result2.hardware=util4.getValue(lines,"kern.hostuuid",":").toLowerCase();if(result2.os.indexOf("unknown")>=0){result2.os=""}if(result2.hardware.indexOf("unknown")>=0){result2.hardware=""}if(callback){callback(result2)}resolve(result2)})}if(_windows){let sysdir="%windir%\\System32";if(process.arch==="ia32"&&Object.prototype.hasOwnProperty.call(process.env,"PROCESSOR_ARCHITEW6432")){sysdir="%windir%\\sysnative\\cmd.exe /c %windir%\\System32"}util4.powerShell("Get-CimInstance Win32_ComputerSystemProduct | select UUID | fl").then(stdout=>{let lines=stdout.split("\r\n");result2.hardware=util4.getValue(lines,"uuid",":").toLowerCase();exec3(`${sysdir}\\reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid`,util4.execOptsWin,function(error,stdout2){parts=stdout2.toString().split("\n\r")[0].split("REG_SZ");result2.os=parts.length>1?parts[1].replace(/\r+|\n+|\s+/ig,"").toLowerCase():"";if(callback){callback(result2)}resolve(result2)})})}})})}exports2.uuid=uuid}});var require_cpu=__commonJS({"node_modules/systeminformation/lib/cpu.js"(exports2){"use strict";var os7=require("os");var exec3=require("child_process").exec;var execSync=require("child_process").execSync;var fs13=require("fs");var util4=require_util2();var _platform=process.platform;var _linux=_platform==="linux"||_platform==="android";var _darwin=_platform==="darwin";var _windows=_platform==="win32";var _freebsd=_platform==="freebsd";var _openbsd=_platform==="openbsd";var _netbsd=_platform==="netbsd";var _sunos=_platform==="sunos";var _cpu_speed=0;var _current_cpu={user:0,nice:0,system:0,idle:0,irq:0,steal:0,guest:0,load:0,tick:0,ms:0,currentLoad:0,currentLoadUser:0,currentLoadSystem:0,currentLoadNice:0,currentLoadIdle:0,currentLoadIrq:0,currentLoadSteal:0,currentLoadGuest:0,rawCurrentLoad:0,rawCurrentLoadUser:0,rawCurrentLoadSystem:0,rawCurrentLoadNice:0,rawCurrentLoadIdle:0,rawCurrentLoadIrq:0,rawCurrentLoadSteal:0,rawCurrentLoadGuest:0};var _cpus=[];var _corecount=0;var AMDBaseFrequencies={"8346":"1.8","8347":"1.9","8350":"2.0","8354":"2.2","8356|SE":"2.4","8356":"2.3","8360":"2.5","2372":"2.1","2373":"2.1","2374":"2.2","2376":"2.3","2377":"2.3","2378":"2.4","2379":"2.4","2380":"2.5","2381":"2.5","2382":"2.6","2384":"2.7","2386":"2.8","2387":"2.8","2389":"2.9","2393":"3.1","8374":"2.2","8376":"2.3","8378":"2.4","8379":"2.4","8380":"2.5","8381":"2.5","8382":"2.6","8384":"2.7","8386":"2.8","8387":"2.8","8389":"2.9","8393":"3.1","2419EE":"1.8","2423HE":"2.0","2425HE":"2.1","2427":"2.2","2431":"2.4","2435":"2.6","2439SE":"2.8","8425HE":"2.1","8431":"2.4","8435":"2.6","8439SE":"2.8","4122":"2.2","4130":"2.6","4162EE":"1.7","4164EE":"1.8","4170HE":"2.1","4174HE":"2.3","4176HE":"2.4","4180":"2.6","4184":"2.8","6124HE":"1.8","6128HE":"2.0","6132HE":"2.2","6128":"2.0","6134":"2.3","6136":"2.4","6140":"2.6","6164HE":"1.7","6166HE":"1.8","6168":"1.9","6172":"2.1","6174":"2.2","6176":"2.3","6176SE":"2.3","6180SE":"2.5","3250":"2.5","3260":"2.7","3280":"2.4","4226":"2.7","4228":"2.8","4230":"2.9","4234":"3.1","4238":"3.3","4240":"3.4","4256":"1.6","4274":"2.5","4276":"2.6","4280":"2.8","4284":"3.0","6204":"3.3","6212":"2.6","6220":"3.0","6234":"2.4","6238":"2.6","6262HE":"1.6","6272":"2.1","6274":"2.2","6276":"2.3","6278":"2.4","6282SE":"2.6","6284SE":"2.7","6308":"3.5","6320":"2.8","6328":"3.2","6338P":"2.3","6344":"2.6","6348":"2.8","6366":"1.8","6370P":"2
${BSDName}|"; smartctl -H ${BSDName} | grep overall;`;cmdFullSmart+=`${cmdFullSmart?'printf ",";':""}smartctl -a -j ${BSDName};`})}catch(e){util4.noop()}}if(cmdFullSmart){exec3(cmdFullSmart,{maxBuffer:1024*1024},function(error2,stdout2){try{const data=JSON.parse(`[${stdout2}]`);data.forEach(disk=>{const diskBSDName=disk.smartctl.argv[disk.smartctl.argv.length-1];for(let i=0;i<result2.length;i++){if(result2[i].BSDName===diskBSDName){result2[i].smartStatus=disk.smart_status.passed?"Ok":disk.smart_status.passed===false?"Predicted Failure":"unknown";if(disk.temperature&&disk.temperature.current){result2[i].temperature=disk.temperature.current}result2[i].smartData=disk}}});commitResult(result2)}catch(e){if(cmd){cmd=cmd+'printf "\n"';exec3(cmd,{maxBuffer:1024*1024},function(error3,stdout3){let lines=stdout3.toString().split("\n");lines.forEach(line=>{if(line){let parts=line.split("|");if(parts.length===2){let BSDName=parts[0];parts[1]=parts[1].trim();let parts2=parts[1].split(":");if(parts2.length===2){parts2[1]=parts2[1].trim();let status=parts2[1].toLowerCase();for(let i=0;i<result2.length;i++){if(result2[i].BSDName===BSDName){result2[i].smartStatus=status==="passed"?"Ok":status==="failed!"?"Predicted Failure":"unknown"}}}}}});commitResult(result2)})}else{commitResult(result2)}}})}else{commitResult(result2)}})}if(_freebsd||_openbsd||_netbsd){if(callback){callback(result2)}resolve(result2)}if(_sunos){if(callback){callback(result2)}resolve(result2)}if(_darwin){exec3("system_profiler SPSerialATADataType SPNVMeDataType SPUSBDataType",{maxBuffer:1024*1024},function(error,stdout){if(!error){let lines=stdout.toString().split("\n");let linesSATA=[];let linesNVMe=[];let linesUSB=[];let dataType="SATA";lines.forEach(line=>{if(line==="NVMExpress:"){dataType="NVMe"}else if(line==="USB:"){dataType="USB"}else if(line==="SATA/SATA Express:"){dataType="SATA"}else if(dataType==="SATA"){linesSATA.push(line)}else if(dataType==="NVMe"){linesNVMe.push(line)}else if(dataType==="USB"){linesUSB.push(line)}});try{let devices=linesSATA.join("\n").split(" Physical Interconnect: ");devices.shift();devices.forEach(function(device){device="InterfaceType: "+device;let lines2=device.split("\n");const mediumType=util4.getValue(lines2,"Medium Type",":",true).trim();const sizeStr=util4.getValue(lines2,"capacity",":",true).trim();const BSDName=util4.getValue(lines2,"BSD Name",":",true).trim();if(sizeStr){let sizeValue=0;if(sizeStr.indexOf("(")>=0){sizeValue=parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g,"").replace(/,/g,"").replace(/\s/g,""))}if(!sizeValue){sizeValue=parseInt(sizeStr)}if(sizeValue){const smartStatusString=util4.getValue(lines2,"S.M.A.R.T. status",":",true).trim().toLowerCase();result2.push({device:BSDName,type:mediumType.startsWith("Solid")?"SSD":"HD",name:util4.getValue(lines2,"Model",":",true).trim(),vendor:getVendorFromModel(util4.getValue(lines2,"Model",":",true).trim())||util4.getValue(lines2,"Manufacturer",":",true),size:sizeValue,bytesPerSector:null,totalCylinders:null,totalHeads:null,totalSectors:null,totalTracks:null,tracksPerCylinder:null,sectorsPerTrack:null,firmwareRevision:util4.getValue(lines2,"Revision",":",true).trim(),serialNum:util4.getValue(lines2,"Serial Number",":",true).trim(),interfaceType:util4.getValue(lines2,"InterfaceType",":",true).trim(),smartStatus:smartStatusString==="verified"?"OK":smartStatusString||"unknown",temperature:null,BSDName});cmd=cmd+'printf "\n'+BSDName+'|"; diskutil info /dev/'+BSDName+" | grep SMART;"}}})}catch(e){util4.noop()}try{let devices=linesNVMe.join("\n").split("\n\n Capacity:");devices.shift();devices.forEach(function(device){device="!Capacity: "+device;let lines2=device.split("\n");const linkWidth=util4.getValue(lines2,"link width",":",true).trim();const sizeStr=util4.getValue(lines2,"!capacity",":",true).trim();const BSDName=util4.getValue(lines2,"BSD Name",":",true).trim();if(sizeStr){let sizeValue=0;if(sizeStr.indexOf("(")>=0){sizeValue=parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g,"").replace(/,/g,"").replace(/\s/g,""))}if(!sizeValue){sizeValue=parseInt(size
echo -n "address: "; cat /sys/class/net/${ifaceSanitized}/address 2>/dev/null; echo;
echo -n "addr_len: "; cat /sys/class/net/${ifaceSanitized}/addr_len 2>/dev/null; echo;
echo -n "broadcast: "; cat /sys/class/net/${ifaceSanitized}/broadcast 2>/dev/null; echo;
echo -n "carrier: "; cat /sys/class/net/${ifaceSanitized}/carrier 2>/dev/null; echo;
echo -n "carrier_changes: "; cat /sys/class/net/${ifaceSanitized}/carrier_changes 2>/dev/null; echo;
echo -n "dev_id: "; cat /sys/class/net/${ifaceSanitized}/dev_id 2>/dev/null; echo;
echo -n "dev_port: "; cat /sys/class/net/${ifaceSanitized}/dev_port 2>/dev/null; echo;
echo -n "dormant: "; cat /sys/class/net/${ifaceSanitized}/dormant 2>/dev/null; echo;
echo -n "duplex: "; cat /sys/class/net/${ifaceSanitized}/duplex 2>/dev/null; echo;
echo -n "flags: "; cat /sys/class/net/${ifaceSanitized}/flags 2>/dev/null; echo;
echo -n "gro_flush_timeout: "; cat /sys/class/net/${ifaceSanitized}/gro_flush_timeout 2>/dev/null; echo;
echo -n "ifalias: "; cat /sys/class/net/${ifaceSanitized}/ifalias 2>/dev/null; echo;
echo -n "ifindex: "; cat /sys/class/net/${ifaceSanitized}/ifindex 2>/dev/null; echo;
echo -n "iflink: "; cat /sys/class/net/${ifaceSanitized}/iflink 2>/dev/null; echo;
echo -n "link_mode: "; cat /sys/class/net/${ifaceSanitized}/link_mode 2>/dev/null; echo;
echo -n "mtu: "; cat /sys/class/net/${ifaceSanitized}/mtu 2>/dev/null; echo;
echo -n "netdev_group: "; cat /sys/class/net/${ifaceSanitized}/netdev_group 2>/dev/null; echo;
echo -n "operstate: "; cat /sys/class/net/${ifaceSanitized}/operstate 2>/dev/null; echo;
echo -n "proto_down: "; cat /sys/class/net/${ifaceSanitized}/proto_down 2>/dev/null; echo;
echo -n "speed: "; cat /sys/class/net/${ifaceSanitized}/speed 2>/dev/null; echo;
echo -n "tx_queue_len: "; cat /sys/class/net/${ifaceSanitized}/tx_queue_len 2>/dev/null; echo;
echo -n "type: "; cat /sys/class/net/${ifaceSanitized}/type 2>/dev/null; echo;
echo -n "wireless: "; cat /proc/net/wireless 2>/dev/null | grep ${ifaceSanitized}; echo;
echo -n "wirelessspeed: "; iw dev ${ifaceSanitized} link 2>&1 | grep bitrate; echo;`;let lines=[];try{lines=execSync(cmd,util4.execOptsLinux).toString().split("\n");const connectionName=getLinuxIfaceConnectionName(ifaceSanitized);dhcp=getLinuxIfaceDHCPstatus(ifaceSanitized,connectionName,_dhcpNics);dnsSuffix=getLinuxIfaceDNSsuffix(connectionName);ieee8021xAuth=getLinuxIfaceIEEE8021xAuth(connectionName);ieee8021xState=getLinuxIfaceIEEE8021xState(ieee8021xAuth)}catch(e){util4.noop()}duplex=util4.getValue(lines,"duplex");duplex=duplex.startsWith("cat")?"":duplex;mtu=parseInt(util4.getValue(lines,"mtu"),10);let myspeed=parseInt(util4.getValue(lines,"speed"),10);speed=isNaN(myspeed)?null:myspeed;let wirelessspeed=util4.getValue(lines,"wirelessspeed").split("tx bitrate: ");if(speed===null&&wirelessspeed.length===2){myspeed=parseFloat(wirelessspeed[1]);speed=isNaN(myspeed)?null:myspeed}carrierChanges=parseInt(util4.getValue(lines,"carrier_changes"),10);const operstate=util4.getValue(lines,"operstate");type2=operstate==="up"?util4.getValue(lines,"wireless").trim()?"wireless":"wired":"unknown";if(ifaceSanitized==="lo"||ifaceSanitized.startsWith("bond")){type2="virtual"}let internal=ifaces[dev]&&ifaces[dev][0]?ifaces[dev][0].internal:false;if(dev.toLowerCase().indexOf("loopback")>-1||ifaceName.toLowerCase().indexOf("loopback")>-1){internal=true}const virtual=internal?false:testVirtualNic(dev,ifaceName,mac);result2.push({iface:ifaceSanitized,ifaceName,default:iface===defaultInterface,ip4,ip4subnet,ip6,ip6subnet,mac,internal,virtual,operstate,type:type2,duplex,mtu,speed,dhcp,dnsSuffix,ieee8021xAuth,ieee8021xState,carrierChanges})}}_networkInterfaces=result2;if(defaultString.toLowerCase().indexOf("default")>=0){result2=result2.filter(item=>item.default);if(result2.length>0){result2=result2[0]}else{result2=[]}}if(callback){callback(result2)}resolve(result2)}}if(_windows){if(JSON.stringify(ifaces)===JSON.stringify(_ifaces)&&!rescan){result2=_networkInterfaces;if(callback){callback(result2)}resolve(result2)}else{_ifaces=JSON.parse(JSON.stringify(ifaces));const defaultInterface=getDefaultNetworkInterface();getWindowsNics().then(function(nics2){nics2.forEach(nic=>{let found=false;Object.keys(ifaces).forEach(key=>{if(!found){ifaces[key].forEach(value=>{if(Object.keys(value).indexOf("mac")>=0){found=value["mac"]===nic.mac}})}});if(!found){ifaces[nic.name]=[{mac:nic.mac}]}});nics8021xInfo=getWindowsWiredProfilesInformation();dnsSuffixes=getWindowsDNSsuffixes();for(let dev in ifaces){let ifaceSanitized="";const s=util4.isPrototypePolluted()?"---":util4.sanitizeShellString(dev);const l=util4.mathMin(s.length,2e3);for(let i=0;i<=l;i++){if(s[i]!==void 0){ifaceSanitized=ifaceSanitized+s[i]}}let iface=dev;let ip4="";let ip4subnet="";let ip6="";let ip6subnet="";let mac="";let duplex="";let mtu="";let speed=null;let carrierChanges=0;let operstate="down";let dhcp=false;let dnsSuffix="";let ieee8021xAuth="";let ieee8021xState="";let type2="";if({}.hasOwnProperty.call(ifaces,dev)){let ifaceName=dev;ifaces[dev].forEach(function(details){if(details.family==="IPv4"||details.family===4){ip4=details.address;ip4subnet=details.netmask}if(details.family==="IPv6"||details.family===6){if(!ip6||ip6.match(/^fe80::/i)){ip6=details.address;ip6subnet=details.netmask}}mac=details.mac;const nodeMainVersion=parseInt(process.versions.node.split("."),10);if(mac.indexOf("00:00:0")>-1&&(_linux||_darwin)&&!details.internal&&nodeMainVersion>=8&&nodeMainVersion<=11){if(Object.keys(_mac).length===0){_mac=getMacAddresses()}mac=_mac[dev]||""}});dnsSuffix=getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces,ifaceSanitized);let foundFirst=false;nics2.forEach(detail=>{if(detail.mac===mac&&!foundFirst){iface=detail.iface||iface;ifaceName=detail.name;dhcp=detail.dhcp;operstate=detail.operstate;speed=operstate==="up"?detail.speed:0;type2=detail.type;foundFirst=true}});if(dev.toLowerCase().indexOf("wlan")>=0||ifaceName.toLowerCase().indexOf("wlan")>=0||ifaceName.toLowerCase().indexOf("802.11n")>=0||ifaceName.toLowerCase().indexOf("wireless")>=0||ifaceName.toLowerCase().indexOf("wi-f
see https://github.com/jprichardson/node-fs-extra/issues/269`)}const{srcStat,destStat}=stat3.checkPathsSync(src,dest,"copy");stat3.checkParentPathsSync(src,srcStat,dest,"copy");return handleFilterAndCopy(destStat,src,dest,opts)}function handleFilterAndCopy(destStat,src,dest,opts){if(opts.filter&&!opts.filter(src,dest))return;const destParent=path24.dirname(dest);if(!fs13.existsSync(destParent))mkdirsSync(destParent);return startCopy(destStat,src,dest,opts)}function startCopy(destStat,src,dest,opts){if(opts.filter&&!opts.filter(src,dest))return;return getStats(destStat,src,dest,opts)}function getStats(destStat,src,dest,opts){const statSync=opts.dereference?fs13.statSync:fs13.lstatSync;const srcStat=statSync(src);if(srcStat.isDirectory())return onDir(srcStat,destStat,src,dest,opts);else if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return onFile(srcStat,destStat,src,dest,opts);else if(srcStat.isSymbolicLink())return onLink(destStat,src,dest,opts)}function onFile(srcStat,destStat,src,dest,opts){if(!destStat)return copyFile(srcStat,src,dest,opts);return mayCopyFile(srcStat,src,dest,opts)}function mayCopyFile(srcStat,src,dest,opts){if(opts.overwrite){fs13.unlinkSync(dest);return copyFile(srcStat,src,dest,opts)}else if(opts.errorOnExist){throw new Error(`'${dest}' already exists`)}}function copyFile(srcStat,src,dest,opts){fs13.copyFileSync(src,dest);if(opts.preserveTimestamps)handleTimestamps(srcStat.mode,src,dest);return setDestMode(dest,srcStat.mode)}function handleTimestamps(srcMode,src,dest){if(fileIsNotWritable(srcMode))makeFileWritable(dest,srcMode);return setDestTimestamps(src,dest)}function fileIsNotWritable(srcMode){return(srcMode&128)===0}function makeFileWritable(dest,srcMode){return setDestMode(dest,srcMode|128)}function setDestMode(dest,srcMode){return fs13.chmodSync(dest,srcMode)}function setDestTimestamps(src,dest){const updatedSrcStat=fs13.statSync(src);return utimesMillisSync(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}function onDir(srcStat,destStat,src,dest,opts){if(!destStat)return mkDirAndCopy(srcStat.mode,src,dest,opts);if(destStat&&!destStat.isDirectory()){throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)}return copyDir(src,dest,opts)}function mkDirAndCopy(srcMode,src,dest,opts){fs13.mkdirSync(dest);copyDir(src,dest,opts);return setDestMode(dest,srcMode)}function copyDir(src,dest,opts){fs13.readdirSync(src).forEach(item=>copyDirItem(item,src,dest,opts))}function copyDirItem(item,src,dest,opts){const srcItem=path24.join(src,item);const destItem=path24.join(dest,item);const{destStat}=stat3.checkPathsSync(srcItem,destItem,"copy");return startCopy(destStat,srcItem,destItem,opts)}function onLink(destStat,src,dest,opts){let resolvedSrc=fs13.readlinkSync(src);if(opts.dereference){resolvedSrc=path24.resolve(process.cwd(),resolvedSrc)}if(!destStat){return fs13.symlinkSync(resolvedSrc,dest)}else{let resolvedDest;try{resolvedDest=fs13.readlinkSync(dest)}catch(err){if(err.code==="EINVAL"||err.code==="UNKNOWN")return fs13.symlinkSync(resolvedSrc,dest);throw err}if(opts.dereference){resolvedDest=path24.resolve(process.cwd(),resolvedDest)}if(stat3.isSrcSubdir(resolvedSrc,resolvedDest)){throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)}if(fs13.statSync(dest).isDirectory()&&stat3.isSrcSubdir(resolvedDest,resolvedSrc)){throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)}return copyLink(resolvedSrc,dest)}}function copyLink(resolvedSrc,dest){fs13.unlinkSync(dest);return fs13.symlinkSync(resolvedSrc,dest)}module2.exports=copySync}});var require_copy_sync2=__commonJS({"node_modules/fs-extra/lib/copy-sync/index.js"(exports2,module2){"use strict";module2.exports={copySync:require_copy_sync()}}});var require_path_exists=__commonJS({"node_modules/fs-extra/lib/path-exists/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise;var fs13=require_fs();function pathExists(path24){return fs13.access(path24).then(()=>true).catch(()=>false)}module2.exports={pathExists:u(p
see https://github.com/jprichardson/node-fs-extra/issues/269`)}stat3.checkPaths(src,dest,"copy",(err,stats)=>{if(err)return cb(err);const{srcStat,destStat}=stats;stat3.checkParentPaths(src,srcStat,dest,"copy",err2=>{if(err2)return cb(err2);if(opts.filter)return handleFilter(checkParentDir,destStat,src,dest,opts,cb);return checkParentDir(destStat,src,dest,opts,cb)})})}function checkParentDir(destStat,src,dest,opts,cb){const destParent=path24.dirname(dest);pathExists(destParent,(err,dirExists)=>{if(err)return cb(err);if(dirExists)return startCopy(destStat,src,dest,opts,cb);mkdirs(destParent,err2=>{if(err2)return cb(err2);return startCopy(destStat,src,dest,opts,cb)})})}function handleFilter(onInclude,destStat,src,dest,opts,cb){Promise.resolve(opts.filter(src,dest)).then(include=>{if(include)return onInclude(destStat,src,dest,opts,cb);return cb()},error=>cb(error))}function startCopy(destStat,src,dest,opts,cb){if(opts.filter)return handleFilter(getStats,destStat,src,dest,opts,cb);return getStats(destStat,src,dest,opts,cb)}function getStats(destStat,src,dest,opts,cb){const stat4=opts.dereference?fs13.stat:fs13.lstat;stat4(src,(err,srcStat)=>{if(err)return cb(err);if(srcStat.isDirectory())return onDir(srcStat,destStat,src,dest,opts,cb);else if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return onFile(srcStat,destStat,src,dest,opts,cb);else if(srcStat.isSymbolicLink())return onLink(destStat,src,dest,opts,cb)})}function onFile(srcStat,destStat,src,dest,opts,cb){if(!destStat)return copyFile(srcStat,src,dest,opts,cb);return mayCopyFile(srcStat,src,dest,opts,cb)}function mayCopyFile(srcStat,src,dest,opts,cb){if(opts.overwrite){fs13.unlink(dest,err=>{if(err)return cb(err);return copyFile(srcStat,src,dest,opts,cb)})}else if(opts.errorOnExist){return cb(new Error(`'${dest}' already exists`))}else return cb()}function copyFile(srcStat,src,dest,opts,cb){fs13.copyFile(src,dest,err=>{if(err)return cb(err);if(opts.preserveTimestamps)return handleTimestampsAndMode(srcStat.mode,src,dest,cb);return setDestMode(dest,srcStat.mode,cb)})}function handleTimestampsAndMode(srcMode,src,dest,cb){if(fileIsNotWritable(srcMode)){return makeFileWritable(dest,srcMode,err=>{if(err)return cb(err);return setDestTimestampsAndMode(srcMode,src,dest,cb)})}return setDestTimestampsAndMode(srcMode,src,dest,cb)}function fileIsNotWritable(srcMode){return(srcMode&128)===0}function makeFileWritable(dest,srcMode,cb){return setDestMode(dest,srcMode|128,cb)}function setDestTimestampsAndMode(srcMode,src,dest,cb){setDestTimestamps(src,dest,err=>{if(err)return cb(err);return setDestMode(dest,srcMode,cb)})}function setDestMode(dest,srcMode,cb){return fs13.chmod(dest,srcMode,cb)}function setDestTimestamps(src,dest,cb){fs13.stat(src,(err,updatedSrcStat)=>{if(err)return cb(err);return utimesMillis(dest,updatedSrcStat.atime,updatedSrcStat.mtime,cb)})}function onDir(srcStat,destStat,src,dest,opts,cb){if(!destStat)return mkDirAndCopy(srcStat.mode,src,dest,opts,cb);if(destStat&&!destStat.isDirectory()){return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))}return copyDir(src,dest,opts,cb)}function mkDirAndCopy(srcMode,src,dest,opts,cb){fs13.mkdir(dest,err=>{if(err)return cb(err);copyDir(src,dest,opts,err2=>{if(err2)return cb(err2);return setDestMode(dest,srcMode,cb)})})}function copyDir(src,dest,opts,cb){fs13.readdir(src,(err,items)=>{if(err)return cb(err);return copyDirItems(items,src,dest,opts,cb)})}function copyDirItems(items,src,dest,opts,cb){const item=items.pop();if(!item)return cb();return copyDirItem(items,item,src,dest,opts,cb)}function copyDirItem(items,item,src,dest,opts,cb){const srcItem=path24.join(src,item);const destItem=path24.join(dest,item);stat3.checkPaths(srcItem,destItem,"copy",(err,stats)=>{if(err)return cb(err);const{destStat}=stats;startCopy(destStat,srcItem,destItem,opts,err2=>{if(err2)return cb(err2);return copyDirItems(items,src,dest,opts,cb)})})}function onLink(destStat,src,dest,opts,cb){fs13.readlink(src,(err,resolvedSrc)=>{if(err)return cb(err);if(opts.dereference){resolvedSrc=path24.reso
${msg}:
`);console.log(`${highlightFn(code)}
`)}exports2.printDebugWithCode=printDebugWithCode;function typeMatch(type2,list,Types){if(Array.isArray(list)){return list.some(t=>type2===Types[t])}return!!list}exports2.typeMatch=typeMatch;var privateObjectProps=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__"]);exports2.privateObjectProps=privateObjectProps;var fieldEscape=field=>{if(privateObjectProps.has(field)){throw new Error(`The field name (${field}) can't be the same as an object's private property.`)}return srcEscape(field)};exports2.fieldEscape=fieldEscape}});var require_is_property=__commonJS({"node_modules/is-property/is-property.js"(exports2,module2){"use strict";function isProperty(str2){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\u
<head>
<title>Requesting Authorization</title>
</head>
<body onload="javascript:document.forms[0].submit()">
<form method="post" action="${this.issuer.authorization_endpoint}">
${formInputs}
</form>
</body>
</html>`}endSessionUrl(params={}){assertIssuerConfiguration(this.issuer,"end_session_endpoint");const{0:postLogout,length}=this.post_logout_redirect_uris||[];const{post_logout_redirect_uri=length===1?postLogout:void 0}=params;let id_token_hint;({id_token_hint,...params}=params);if(id_token_hint instanceof TokenSet2){if(!id_token_hint.id_token){throw new TypeError("id_token not present in TokenSet")}id_token_hint=id_token_hint.id_token}const target=url.parse(this.issuer.end_session_endpoint);const query=defaults3(getSearchParams(this.issuer.end_session_endpoint),params,{post_logout_redirect_uri,client_id:this.client_id},{id_token_hint});Object.entries(query).forEach(([key,value])=>{if(value===null||value===void 0){delete query[key]}});target.search=null;target.query=query;return url.format(target)}callbackParams(input){const isIncomingMessage=input instanceof stdhttp.IncomingMessage||input&&input.method&&input.url;const isString3=typeof input==="string";if(!isString3&&!isIncomingMessage){throw new TypeError("#callbackParams only accepts string urls, http.IncomingMessage or a lookalike")}if(isIncomingMessage){switch(input.method){case"GET":return pickCb(getSearchParams(input.url));case"POST":if(input.body===void 0){throw new TypeError("incoming message body missing, include a body parser prior to this method call")}switch(typeof input.body){case"object":case"string":if(Buffer.isBuffer(input.body)){return pickCb(querystring.parse(input.body.toString("utf-8")))}if(typeof input.body==="string"){return pickCb(querystring.parse(input.body))}return pickCb(input.body);default:throw new TypeError("invalid IncomingMessage body object")}default:throw new TypeError("invalid IncomingMessage method")}}else{return pickCb(getSearchParams(input))}}async callback(redirectUri,parameters,checks2={},{exchangeBody,clientAssertionPayload,DPoP}={}){let params=pickCb(parameters);if(checks2.jarm&&!("response"in parameters)){throw new RPError({message:"expected a JARM response",checks:checks2,params})}else if("response"in parameters){const decrypted=await this.decryptJARM(params.response);params=await this.validateJARM(decrypted)}if(this.default_max_age&&!checks2.max_age){checks2.max_age=this.default_max_age}if(params.state&&!checks2.state){throw new TypeError("checks.state argument is missing")}if(!params.state&&checks2.state){throw new RPError({message:"state missing from the response",checks:checks2,params})}if(checks2.state!==params.state){throw new RPError({printf:["state mismatch, expected %s, got: %s",checks2.state,params.state],checks:checks2,params})}if("iss"in params){assertIssuerConfiguration(this.issuer,"issuer");if(params.iss!==this.issuer.issuer){throw new RPError({printf:["iss mismatch, expected %s, got: %s",this.issuer.issuer,params.iss],params})}}else if(this.issuer.authorization_response_iss_parameter_supported&&!("id_token"in params)&&!("response"in parameters)){throw new RPError({message:"iss missing from the response",params})}if(params.error){throw new OPError(params)}const RESPONSE_TYPE_REQUIRED_PARAMS={code:["code"],id_token:["id_token"],token:["access_token","token_type"]};if(checks2.response_type){for(const type2 of checks2.response_type.split(" ")){if(type2==="none"){if(params.code||params.id_token||params.access_token){throw new RPError({message:'unexpected params encountered for "none" response',checks:checks2,params})}}else{for(const param of RESPONSE_TYPE_REQUIRED_PARAMS[type2]){if(!params[param]){throw new RPError({message:`${param} missing from response`,checks:checks2,params})}}}}}if(params.id_token){const tokenset=new TokenSet2(params);await this.decryptIdToken(tokenset);await this.validateIdToken(tokenset,checks2.nonce,"authorization",checks2.max_age,checks2.state);if(!params.code){return tokenset}}if(params.code){const tokenset=await this.grant({...exchangeBody,grant_type:"authorization_code",code:params.code,redirect_uri:redirectUri,code_verifier:checks2.code_verifier},{clientAssertionPayload,DPoP});await this.decryptIdToken(tokenset);await this.validateIdToken(tokenset,checks2.nonce,"token",checks2.max_age);i
Content-Disposition: form-data`;const escape3=str2=>str2.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=value=>value.replace(/\r?\n|\r/g,"\r\n");const blobParts=[];const rn=new Uint8Array([13,10]);length=0;let hasUnknownSizeValue=false;for(const[name,value]of object){if(typeof value==="string"){const chunk3=textEncoder.encode(prefix+`; name="${escape3(normalizeLinefeeds(name))}"\r
\r
${normalizeLinefeeds(value)}\r
`);blobParts.push(chunk3);length+=chunk3.byteLength}else{const chunk3=textEncoder.encode(`${prefix}; name="${escape3(normalizeLinefeeds(name))}"`+(value.name?`; filename="${escape3(value.name)}"`:"")+`\r
Content-Type: ${value.type||"application/octet-stream"}\r
\r
`);blobParts.push(chunk3,value,rn);if(typeof value.size==="number"){length+=chunk3.byteLength+value.size+rn.byteLength}else{hasUnknownSizeValue=true}}}const chunk2=textEncoder.encode(`--${boundary}--`);blobParts.push(chunk2);length+=chunk2.byteLength;if(hasUnknownSizeValue){length=null}source=object;action=async function*(){for(const part of blobParts){if(part.stream){yield*part.stream()}else{yield part}}};type2="multipart/form-data; boundary="+boundary}else if(isBlobLike(object)){source=object;length=object.size;if(object.type){type2=object.type}}else if(typeof object[Symbol.asyncIterator]==="function"){if(keepalive){throw new TypeError("keepalive")}if(util4.isDisturbed(object)||object.locked){throw new TypeError("Response body object should not be disturbed or locked")}stream3=object instanceof ReadableStream2?object:ReadableStreamFrom(object)}if(typeof source==="string"||util4.isBuffer(source)){length=Buffer.byteLength(source)}if(action!=null){let iterator;stream3=new ReadableStream2({async start(){iterator=action(object)[Symbol.asyncIterator]()},async pull(controller){const{value,done}=await iterator.next();if(done){queueMicrotask(()=>{controller.close()})}else{if(!isErrored(stream3)){controller.enqueue(new Uint8Array(value))}}return controller.desiredSize>0},async cancel(reason){await iterator.return()},type:void 0})}const body={stream:stream3,source,length};return[body,type2]}function safelyExtractBody(object,keepalive=false){if(!ReadableStream2){ReadableStream2=require("stream/web").ReadableStream}if(object instanceof ReadableStream2){assert2(!util4.isDisturbed(object),"The body has already been consumed.");assert2(!object.locked,"The stream is locked.")}return extractBody(object,keepalive)}function cloneBody(body){const[out1,out2]=body.stream.tee();const out2Clone=structuredClone2(out2,{transfer:[out2]});const[,finalClone]=out2Clone.tee();body.stream=out1;return{stream:finalClone,length:body.length,source:body.source}}async function*consumeBody(body){if(body){if(isUint8Array(body)){yield body}else{const stream3=body.stream;if(util4.isDisturbed(stream3)){throw new TypeError("The body has already been consumed.")}if(stream3.locked){throw new TypeError("The stream is locked.")}stream3[kBodyUsed]=true;yield*stream3}}}function throwIfAborted(state){if(state.aborted){throw new DOMException2("The operation was aborted.","AbortError")}}function bodyMixinMethods(instance){const methods={blob(){return specConsumeBody(this,bytes8=>{let mimeType=bodyMimeType(this);if(mimeType==="failure"){mimeType=""}else if(mimeType){mimeType=serializeAMimeType(mimeType)}return new Blob2([bytes8],{type:mimeType})},instance)},arrayBuffer(){return specConsumeBody(this,bytes8=>{return new Uint8Array(bytes8).buffer},instance)},text(){return specConsumeBody(this,utf8DecodeBytes,instance)},json(){return specConsumeBody(this,parseJSONFromBytes,instance)},async formData(){webidl.brandCheck(this,instance);throwIfAborted(this[kState]);const contentType=this.headers.get("Content-Type");if(/multipart\/form-data/.test(contentType)){const headers={};for(const[key,value]of this.headers)headers[key.toLowerCase()]=value;const responseFormData=new FormData;let busboy;try{busboy=new Busboy({headers,preservePath:true})}catch(err){throw new DOMException2(`${err}`,"AbortError")}busboy.on("field",(name,value)=>{responseFormData.append(name,value)});busboy.on("file",(name,value,filename,encoding,mimeType)=>{const chunks=[];if(encoding==="base64"||encoding.toLowerCase()==="base64"){let base64chunk="";value.on("data",chunk2=>{base64chunk+=chunk2.toString().replace(/[\r\n]/gm,"");const end=base64chunk.length-base64chunk.length%4;chunks.push(Buffer.from(base64chunk.slice(0,end),"base64"));base64chunk=base64chunk.slice(end)});value.on("end",()=>{chunks.push(Buffer.from(base64chunk,"base64"));responseFormData.append(name,new File2(chunks,filename,{type:mimeType}))})}else{value.on("data",chunk2=>{chunks.push(chunk2)});value.on("end",()=>{responseFormData.append(name,new File2(chunks,filename,{type:mimeType}))})}});const busboyResolve=new Promise((resolve,reject2)=>{busb
`}this.body=bodyStream.stream;this.contentLength=bodyStream.length}else if(util4.isBlobLike(body)&&this.contentType==null&&body.type){this.contentType=body.type;this.headers+=`content-type: ${body.type}\r
`}util4.validateHandler(handler,method2,upgrade);this.servername=util4.getServerName(this.host);this[kHandler]=handler;if(channels.create.hasSubscribers){channels.create.publish({request:this})}}onBodySent(chunk2){if(this[kHandler].onBodySent){try{return this[kHandler].onBodySent(chunk2)}catch(err){this.abort(err)}}}onRequestSent(){if(channels.bodySent.hasSubscribers){channels.bodySent.publish({request:this})}if(this[kHandler].onRequestSent){try{return this[kHandler].onRequestSent()}catch(err){this.abort(err)}}}onConnect(abort){assert2(!this.aborted);assert2(!this.completed);if(this.error){abort(this.error)}else{this.abort=abort;return this[kHandler].onConnect(abort)}}onHeaders(statusCode,headers,resume,statusText){assert2(!this.aborted);assert2(!this.completed);if(channels.headers.hasSubscribers){channels.headers.publish({request:this,response:{statusCode,headers,statusText}})}try{return this[kHandler].onHeaders(statusCode,headers,resume,statusText)}catch(err){this.abort(err)}}onData(chunk2){assert2(!this.aborted);assert2(!this.completed);try{return this[kHandler].onData(chunk2)}catch(err){this.abort(err);return false}}onUpgrade(statusCode,headers,socket){assert2(!this.aborted);assert2(!this.completed);return this[kHandler].onUpgrade(statusCode,headers,socket)}onComplete(trailers){this.onFinally();assert2(!this.aborted);this.completed=true;if(channels.trailers.hasSubscribers){channels.trailers.publish({request:this,trailers})}try{return this[kHandler].onComplete(trailers)}catch(err){this.onError(err)}}onError(error){this.onFinally();if(channels.error.hasSubscribers){channels.error.publish({request:this,error})}if(this.aborted){return}this.aborted=true;return this[kHandler].onError(error)}onFinally(){if(this.errorHandler){this.body.off("error",this.errorHandler);this.errorHandler=null}if(this.endHandler){this.body.off("end",this.endHandler);this.endHandler=null}}addHeader(key,value){processHeader(this,key,value);return this}static[kHTTP1BuildRequest](origin,opts,handler){return new _Request(origin,opts,handler)}static[kHTTP2BuildRequest](origin,opts,handler){const headers=opts.headers;opts={...opts,headers:null};const request=new _Request(origin,opts,handler);request.headers={};if(Array.isArray(headers)){if(headers.length%2!==0){throw new InvalidArgumentError("headers array must be even")}for(let i=0;i<headers.length;i+=2){processHeader(request,headers[i],headers[i+1],true)}}else if(headers&&typeof headers==="object"){const keys2=Object.keys(headers);for(let i=0;i<keys2.length;i++){const key=keys2[i];processHeader(request,key,headers[key],true)}}else if(headers!=null){throw new InvalidArgumentError("headers must be an object or an array")}return request}static[kHTTP2CopyHeaders](raw){const rawHeaders=raw.split("\r\n");const headers={};for(const header2 of rawHeaders){const[key,value]=header2.split(": ");if(value==null||value.length===0)continue;if(headers[key])headers[key]+=`,${value}`;else headers[key]=value}return headers}};function processHeaderValue(key,val,skipAppend){if(val&&typeof val==="object"){throw new InvalidArgumentError(`invalid ${key} header`)}val=val!=null?`${val}`:"";if(headerCharRegex.exec(val)!==null){throw new InvalidArgumentError(`invalid ${key} header`)}return skipAppend?val:`${key}: ${val}\r
`}function processHeader(request,key,val,skipAppend=false){if(val&&(typeof val==="object"&&!Array.isArray(val))){throw new InvalidArgumentError(`invalid ${key} header`)}else if(val===void 0){return}if(request.host===null&&key.length===4&&key.toLowerCase()==="host"){if(headerCharRegex.exec(val)!==null){throw new InvalidArgumentError(`invalid ${key} header`)}request.host=val}else if(request.contentLength===null&&key.length===14&&key.toLowerCase()==="content-length"){request.contentLength=parseInt(val,10);if(!Number.isFinite(request.contentLength)){throw new InvalidArgumentError("invalid content-length header")}}else if(request.contentType===null&&key.length===12&&key.toLowerCase()==="content-type"){request.contentType=val;if(skipAppend)request.headers[key]=processHeaderValue(key,val,skipAppend);else request.headers+=processHeaderValue(key,val)}else if(key.length===17&&key.toLowerCase()==="transfer-encoding"){throw new InvalidArgumentError("invalid transfer-encoding header")}else if(key.length===10&&key.toLowerCase()==="connection"){const value=typeof val==="string"?val.toLowerCase():null;if(value!=="close"&&value!=="keep-alive"){throw new InvalidArgumentError("invalid connection header")}else if(value==="close"){request.reset=true}}else if(key.length===10&&key.toLowerCase()==="keep-alive"){throw new InvalidArgumentError("invalid keep-alive header")}else if(key.length===7&&key.toLowerCase()==="upgrade"){throw new InvalidArgumentError("invalid upgrade header")}else if(key.length===6&&key.toLowerCase()==="expect"){throw new NotSupportedError("expect header not supported")}else if(tokenRegExp.exec(key)===null){throw new InvalidArgumentError("invalid header key")}else{if(Array.isArray(val)){for(let i=0;i<val.length;i++){if(skipAppend){if(request.headers[key])request.headers[key]+=`,${processHeaderValue(key,val[i],skipAppend)}`;else request.headers[key]=processHeaderValue(key,val[i],skipAppend)}else{request.headers+=processHeaderValue(key,val[i])}}}else{if(skipAppend)request.headers[key]=processHeaderValue(key,val,skipAppend);else request.headers+=processHeaderValue(key,val)}}}module2.exports=Request2}});var require_dispatcher=__commonJS({"node_modules/undici/lib/dispatcher.js"(exports2,module2){"use strict";var EventEmitter3=require("events");var Dispatcher=class extends EventEmitter3{dispatch(){throw new Error("not implemented")}close(){throw new Error("not implemented")}destroy(){throw new Error("not implemented")}};module2.exports=Dispatcher}});var require_dispatcher_base=__commonJS({"node_modules/undici/lib/dispatcher-base.js"(exports2,module2){"use strict";var Dispatcher=require_dispatcher();var{ClientDestroyedError,ClientClosedError,InvalidArgumentError}=require_errors5();var{kDestroy,kClose,kDispatch,kInterceptors}=require_symbols();var kDestroyed=Symbol("destroyed");var kClosed=Symbol("closed");var kOnDestroyed=Symbol("onDestroyed");var kOnClosed=Symbol("onClosed");var kInterceptedDispatch=Symbol("Intercepted Dispatch");var DispatcherBase=class extends Dispatcher{constructor(){super();this[kDestroyed]=false;this[kOnDestroyed]=null;this[kClosed]=false;this[kOnClosed]=[]}get destroyed(){return this[kDestroyed]}get closed(){return this[kClosed]}get interceptors(){return this[kInterceptors]}set interceptors(newInterceptors){if(newInterceptors){for(let i=newInterceptors.length-1;i>=0;i--){const interceptor=this[kInterceptors][i];if(typeof interceptor!=="function"){throw new InvalidArgumentError("interceptor must be an function")}}}this[kInterceptors]=newInterceptors}close(callback){if(callback===void 0){return new Promise((resolve,reject2)=>{this.close((err,data)=>{return err?reject2(err):resolve(data)})})}if(typeof callback!=="function"){throw new InvalidArgumentError("invalid callback")}if(this[kDestroyed]){queueMicrotask(()=>callback(new ClientDestroyedError,null));return}if(this[kClosed]){if(this[kOnClosed]){this[kOnClosed].push(callback)}else{queueMicrotask(()=>callback(null,null))}return}this[kClosed]=true;this[kOnClosed].push(callback);const onClosed=()=>{const callbacks=this[kOnClosed];this[kOnClosed]=null;for(let i
`;this[kBodyTimeout]=bodyTimeout!=null?bodyTimeout:3e5;this[kHeadersTimeout]=headersTimeout!=null?headersTimeout:3e5;this[kStrictContentLength]=strictContentLength==null?true:strictContentLength;this[kMaxRedirections]=maxRedirections;this[kMaxRequests]=maxRequestsPerClient;this[kClosedResolve]=null;this[kMaxResponseSize]=maxResponseSize>-1?maxResponseSize:-1;this[kHTTPConnVersion]="h1";this[kHTTP2Session]=null;this[kHTTP2SessionState]=!allowH2?null:{openStreams:0,maxConcurrentStreams:maxConcurrentStreams!=null?maxConcurrentStreams:100};this[kHost]=`${this[kUrl].hostname}${this[kUrl].port?`:${this[kUrl].port}`:""}`;this[kQueue]=[];this[kRunningIdx]=0;this[kPendingIdx]=0}get pipelining(){return this[kPipelining]}set pipelining(value){this[kPipelining]=value;resume(this,true)}get[kPending](){return this[kQueue].length-this[kPendingIdx]}get[kRunning](){return this[kPendingIdx]-this[kRunningIdx]}get[kSize](){return this[kQueue].length-this[kRunningIdx]}get[kConnected](){return!!this[kSocket]&&!this[kConnecting]&&!this[kSocket].destroyed}get[kBusy](){const socket=this[kSocket];return socket&&(socket[kReset]||socket[kWriting]||socket[kBlocking])||this[kSize]>=(this[kPipelining]||1)||this[kPending]>0}[kConnect](cb){connect(this);this.once("connect",cb)}[kDispatch](opts,handler){const origin=opts.origin||this[kUrl].origin;const request=this[kHTTPConnVersion]==="h2"?Request2[kHTTP2BuildRequest](origin,opts,handler):Request2[kHTTP1BuildRequest](origin,opts,handler);this[kQueue].push(request);if(this[kResuming]){}else if(util4.bodyLength(request.body)==null&&util4.isIterable(request.body)){this[kResuming]=1;process.nextTick(resume,this)}else{resume(this,true)}if(this[kResuming]&&this[kNeedDrain]!==2&&this[kBusy]){this[kNeedDrain]=2}return this[kNeedDrain]<2}async[kClose](){return new Promise(resolve=>{if(!this[kSize]){resolve(null)}else{this[kClosedResolve]=resolve}})}async[kDestroy](err){return new Promise(resolve=>{const requests=this[kQueue].splice(this[kPendingIdx]);for(let i=0;i<requests.length;i++){const request=requests[i];errorRequest(this,request,err)}const callback=()=>{if(this[kClosedResolve]){this[kClosedResolve]();this[kClosedResolve]=null}resolve()};if(this[kHTTP2Session]!=null){util4.destroy(this[kHTTP2Session],err);this[kHTTP2Session]=null;this[kHTTP2SessionState]=null}if(!this[kSocket]){queueMicrotask(callback)}else{util4.destroy(this[kSocket].on("close",callback),err)}resume(this)})}};function onHttp2SessionError(err){assert2(err.code!=="ERR_TLS_CERT_ALTNAME_INVALID");this[kSocket][kError]=err;onError(this[kClient],err)}function onHttp2FrameError(type2,code,id){const err=new InformationalError(`HTTP/2: "frameError" received - type ${type2}, code ${code}`);if(id===0){this[kSocket][kError]=err;onError(this[kClient],err)}}function onHttp2SessionEnd(){util4.destroy(this,new SocketError("other side closed"));util4.destroy(this[kSocket],new SocketError("other side closed"))}function onHTTP2GoAway(code){const client=this[kClient];const err=new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`);client[kSocket]=null;client[kHTTP2Session]=null;if(client.destroyed){assert2(this[kPending]===0);const requests=client[kQueue].splice(client[kRunningIdx]);for(let i=0;i<requests.length;i++){const request=requests[i];errorRequest(this,request,err)}}else if(client[kRunning]>0){const request=client[kQueue][client[kRunningIdx]];client[kQueue][client[kRunningIdx]++]=null;errorRequest(client,request,err)}client[kPendingIdx]=client[kRunningIdx];assert2(client[kRunning]===0);client.emit("disconnect",client[kUrl],[client],err);resume(client)}var constants3=require_constants3();var createRedirectInterceptor=require_redirectInterceptor();var EMPTY_BUF=Buffer.alloc(0);async function lazyllhttp(){const llhttpWasmData=process.env.JEST_WORKER_ID?require_llhttp_wasm():void 0;let mod3;try{mod3=await WebAssembly.compile(Buffer.from(require_llhttp_simd_wasm(),"base64"))}catch(e){mod3=await WebAssembly.compile(Buffer.from(llhttpWasmData||require_llhttp_wasm(),"base64"))}return await WebAssembly.instantiate(mod3,{env:{wasm_on_url:(
`;if(typeof host==="string"){header2+=`host: ${host}\r
`}else{header2+=client[kHostHeader]}if(upgrade){header2+=`connection: upgrade\r
upgrade: ${upgrade}\r
`}else if(client[kPipelining]&&!socket[kReset]){header2+="connection: keep-alive\r\n"}else{header2+="connection: close\r\n"}if(headers){header2+=headers}if(channels.sendHeaders.hasSubscribers){channels.sendHeaders.publish({request,headers:header2,socket})}if(!body||bodyLength===0){if(contentLength===0){socket.write(`${header2}content-length: 0\r
\r
`,"latin1")}else{assert2(contentLength===null,"no body must not have content length");socket.write(`${header2}\r
`,"latin1")}request.onRequestSent()}else if(util4.isBuffer(body)){assert2(contentLength===body.byteLength,"buffer body must have content length");socket.cork();socket.write(`${header2}content-length: ${contentLength}\r
\r
`,"latin1");socket.write(body);socket.uncork();request.onBodySent(body);request.onRequestSent();if(!expectsPayload){socket[kReset]=true}}else if(util4.isBlobLike(body)){if(typeof body.stream==="function"){writeIterable({body:body.stream(),client,request,socket,contentLength,header:header2,expectsPayload})}else{writeBlob({body,client,request,socket,contentLength,header:header2,expectsPayload})}}else if(util4.isStream(body)){writeStream({body,client,request,socket,contentLength,header:header2,expectsPayload})}else if(util4.isIterable(body)){writeIterable({body,client,request,socket,contentLength,header:header2,expectsPayload})}else{assert2(false)}return true}function writeH2(client,session,request){const{body,method:method2,path:path24,host,upgrade,expectContinue,signal,headers:reqHeaders}=request;let headers;if(typeof reqHeaders==="string")headers=Request2[kHTTP2CopyHeaders](reqHeaders.trim());else headers=reqHeaders;if(upgrade){errorRequest(client,request,new Error("Upgrade not supported for H2"));return false}try{request.onConnect(err=>{if(request.aborted||request.completed){return}errorRequest(client,request,err||new RequestAbortedError)})}catch(err){errorRequest(client,request,err)}if(request.aborted){return false}let stream3;const h2State=client[kHTTP2SessionState];headers[HTTP2_HEADER_AUTHORITY]=host||client[kHost];headers[HTTP2_HEADER_METHOD]=method2;if(method2==="CONNECT"){session.ref();stream3=session.request(headers,{endStream:false,signal});if(stream3.id&&!stream3.pending){request.onUpgrade(null,null,stream3);++h2State.openStreams}else{stream3.once("ready",()=>{request.onUpgrade(null,null,stream3);++h2State.openStreams})}stream3.once("close",()=>{h2State.openStreams-=1;if(h2State.openStreams===0)session.unref()});return true}headers[HTTP2_HEADER_PATH]=path24;headers[HTTP2_HEADER_SCHEME]="https";const expectsPayload=method2==="PUT"||method2==="POST"||method2==="PATCH";if(body&&typeof body.read==="function"){body.read(0)}let contentLength=util4.bodyLength(body);if(contentLength==null){contentLength=request.contentLength}if(contentLength===0||!expectsPayload){contentLength=null}if(shouldSendContentLength(method2)&&contentLength>0&&request.contentLength!=null&&request.contentLength!==contentLength){if(client[kStrictContentLength]){errorRequest(client,request,new RequestContentLengthMismatchError);return false}process.emitWarning(new RequestContentLengthMismatchError)}if(contentLength!=null){assert2(body,"no body must not have content length");headers[HTTP2_HEADER_CONTENT_LENGTH]=`${contentLength}`}session.ref();const shouldEndStream=method2==="GET"||method2==="HEAD";if(expectContinue){headers[HTTP2_HEADER_EXPECT]="100-continue";stream3=session.request(headers,{endStream:shouldEndStream,signal});stream3.once("continue",writeBodyH2)}else{stream3=session.request(headers,{endStream:shouldEndStream,signal});writeBodyH2()}++h2State.openStreams;stream3.once("response",headers2=>{const{[HTTP2_HEADER_STATUS]:statusCode,...realHeaders}=headers2;if(request.onHeaders(Number(statusCode),realHeaders,stream3.resume.bind(stream3),"")===false){stream3.pause()}});stream3.once("end",()=>{request.onComplete([])});stream3.on("data",chunk2=>{if(request.onData(chunk2)===false){stream3.pause()}});stream3.once("close",()=>{h2State.openStreams-=1;if(h2State.openStreams===0){session.unref()}});stream3.once("error",function(err){if(client[kHTTP2Session]&&!client[kHTTP2Session].destroyed&&!this.closed&&!this.destroyed){h2State.streams-=1;util4.destroy(stream3,err)}});stream3.once("frameError",(type2,code)=>{const err=new InformationalError(`HTTP/2: "frameError" received - type ${type2}, code ${code}`);errorRequest(client,request,err);if(client[kHTTP2Session]&&!client[kHTTP2Session].destroyed&&!this.closed&&!this.destroyed){h2State.streams-=1;util4.destroy(stream3,err)}});return true;function writeBodyH2(){if(!body){request.onRequestSent()}else if(util4.isBuffer(body)){assert2(contentLength===body.byteLength,"buffer body must have content length");stream3.cork();stream3.write(body);stream3.uncork();stream3.end();request.onBodySent(body);reques
\r
`,"latin1");socket.write(buffer);socket.uncork()}request.onBodySent(buffer);request.onRequestSent();if(!expectsPayload){socket[kReset]=true}resume(client)}catch(err){util4.destroy(isH2?h2stream:socket,err)}}async function writeIterable({h2stream,body,client,request,socket,contentLength,header:header2,expectsPayload}){assert2(contentLength!==0||client[kRunning]===0,"iterator body cannot be pipelined");let callback=null;function onDrain(){if(callback){const cb=callback;callback=null;cb()}}const waitForDrain=()=>new Promise((resolve,reject2)=>{assert2(callback===null);if(socket[kError]){reject2(socket[kError])}else{callback=resolve}});if(client[kHTTPConnVersion]==="h2"){h2stream.on("close",onDrain).on("drain",onDrain);try{for await(const chunk2 of body){if(socket[kError]){throw socket[kError]}const res=h2stream.write(chunk2);request.onBodySent(chunk2);if(!res){await waitForDrain()}}}catch(err){h2stream.destroy(err)}finally{request.onRequestSent();h2stream.end();h2stream.off("close",onDrain).off("drain",onDrain)}return}socket.on("close",onDrain).on("drain",onDrain);const writer=new AsyncWriter({socket,request,contentLength,client,expectsPayload,header:header2});try{for await(const chunk2 of body){if(socket[kError]){throw socket[kError]}if(!writer.write(chunk2)){await waitForDrain()}}writer.end()}catch(err){writer.destroy(err)}finally{socket.off("close",onDrain).off("drain",onDrain)}}var AsyncWriter=class{constructor({socket,request,contentLength,client,expectsPayload,header:header2}){this.socket=socket;this.request=request;this.contentLength=contentLength;this.client=client;this.bytesWritten=0;this.expectsPayload=expectsPayload;this.header=header2;socket[kWriting]=true}write(chunk2){const{socket,request,contentLength,client,bytesWritten,expectsPayload,header:header2}=this;if(socket[kError]){throw socket[kError]}if(socket.destroyed){return false}const len=Buffer.byteLength(chunk2);if(!len){return true}if(contentLength!==null&&bytesWritten+len>contentLength){if(client[kStrictContentLength]){throw new RequestContentLengthMismatchError}process.emitWarning(new RequestContentLengthMismatchError)}socket.cork();if(bytesWritten===0){if(!expectsPayload){socket[kReset]=true}if(contentLength===null){socket.write(`${header2}transfer-encoding: chunked\r
`,"latin1")}else{socket.write(`${header2}content-length: ${contentLength}\r
\r
`,"latin1")}}if(contentLength===null){socket.write(`\r
${len.toString(16)}\r
`,"latin1")}this.bytesWritten+=len;const ret=socket.write(chunk2);socket.uncork();request.onBodySent(chunk2);if(!ret){if(socket[kParser].timeout&&socket[kParser].timeoutType===TIMEOUT_HEADERS){if(socket[kParser].timeout.refresh){socket[kParser].timeout.refresh()}}}return ret}end(){const{socket,contentLength,client,bytesWritten,expectsPayload,header:header2,request}=this;request.onRequestSent();socket[kWriting]=false;if(socket[kError]){throw socket[kError]}if(socket.destroyed){return}if(bytesWritten===0){if(expectsPayload){socket.write(`${header2}content-length: 0\r
\r
`,"latin1")}else{socket.write(`${header2}\r
`,"latin1")}}else if(contentLength===null){socket.write("\r\n0\r\n\r\n","latin1")}if(contentLength!==null&&bytesWritten!==contentLength){if(client[kStrictContentLength]){throw new RequestContentLengthMismatchError}else{process.emitWarning(new RequestContentLengthMismatchError)}}if(socket[kParser].timeout&&socket[kParser].timeoutType===TIMEOUT_HEADERS){if(socket[kParser].timeout.refresh){socket[kParser].timeout.refresh()}}resume(client)}destroy(err){const{socket,client}=this;socket[kWriting]=false;if(err){assert2(client[kRunning]<=1,"pipeline should only contain this request");util4.destroy(socket,err)}}};function errorRequest(client,request,err){try{request.onError(err);assert2(request.aborted)}catch(err2){client.emit("error",err2)}}module2.exports=Client3}});var require_fixed_queue=__commonJS({"node_modules/undici/lib/node/fixed-queue.js"(exports2,module2){"use strict";var kSize=2048;var kMask=kSize-1;var FixedCircularBuffer=class{constructor(){this.bottom=0;this.top=0;this.list=new Array(kSize);this.next=null}isEmpty(){return this.top===this.bottom}isFull(){return(this.top+1&kMask)===this.bottom}push(data){this.list[this.top]=data;this.top=this.top+1&kMask}shift(){const nextItem=this.list[this.bottom];if(nextItem===void 0)return null;this.list[this.bottom]=void 0;this.bottom=this.bottom+1&kMask;return nextItem}};module2.exports=class FixedQueue{constructor(){this.head=this.tail=new FixedCircularBuffer}isEmpty(){return this.head.isEmpty()}push(data){if(this.head.isFull()){this.head=this.head.next=new FixedCircularBuffer}this.head.push(data)}shift(){const tail2=this.tail;const next=tail2.shift();if(tail2.isEmpty()&&tail2.next!==null){this.tail=tail2.next}return next}}}});var require_pool_stats=__commonJS({"node_modules/undici/lib/pool-stats.js"(exports2,module2){var{kFree,kConnected,kPending,kQueued,kRunning,kSize}=require_symbols();var kPool=Symbol("pool");var PoolStats=class{constructor(pool2){this[kPool]=pool2}get connected(){return this[kPool][kConnected]}get free(){return this[kPool][kFree]}get pending(){return this[kPool][kPending]}get queued(){return this[kPool][kQueued]}get running(){return this[kPool][kRunning]}get size(){return this[kPool][kSize]}};module2.exports=PoolStats}});var require_pool_base=__commonJS({"node_modules/undici/lib/pool-base.js"(exports2,module2){"use strict";var DispatcherBase=require_dispatcher_base();var FixedQueue=require_fixed_queue();var{kConnected,kSize,kRunning,kPending,kQueued,kBusy,kFree,kUrl,kClose,kDestroy,kDispatch}=require_symbols();var PoolStats=require_pool_stats();var kClients=Symbol("clients");var kNeedDrain=Symbol("needDrain");var kQueue=Symbol("queue");var kClosedResolve=Symbol("closed resolve");var kOnDrain=Symbol("onDrain");var kOnConnect=Symbol("onConnect");var kOnDisconnect=Symbol("onDisconnect");var kOnConnectionError=Symbol("onConnectionError");var kGetDispatcher=Symbol("get dispatcher");var kAddClient=Symbol("add client");var kRemoveClient=Symbol("remove client");var kStats=Symbol("stats");var PoolBase=class extends DispatcherBase{constructor(){super();this[kQueue]=new FixedQueue;this[kClients]=[];this[kQueued]=0;const pool2=this;this[kOnDrain]=function onDrain(origin,targets){const queue=pool2[kQueue];let needDrain=false;while(!needDrain){const item=queue.shift();if(!item){break}pool2[kQueued]--;needDrain=!this.dispatch(item.opts,item.handler)}this[kNeedDrain]=needDrain;if(!this[kNeedDrain]&&pool2[kNeedDrain]){pool2[kNeedDrain]=false;pool2.emit("drain",origin,[pool2,...targets])}if(pool2[kClosedResolve]&&queue.isEmpty()){Promise.all(pool2[kClients].map(c=>c.close())).then(pool2[kClosedResolve])}};this[kOnConnect]=(origin,targets)=>{pool2.emit("connect",origin,[pool2,...targets])};this[kOnDisconnect]=(origin,targets,err)=>{pool2.emit("disconnect",origin,[pool2,...targets],err)};this[kOnConnectionError]=(origin,targets,err)=>{pool2.emit("connectionError",origin,[pool2,...targets],err)};this[kStats]=new PoolStats(this)}get[kBusy](){return this[kNeedDrain]}get[kConnected](){return this[kClients].filter(client=>client[kConnected]).length}get[kFree](){return this[kClie
${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
${pendingInterceptorsFormatter.format(pending)}
`.trim())}};module2.exports=MockAgent}});var require_proxy_agent=__commonJS({"node_modules/undici/lib/proxy-agent.js"(exports2,module2){"use strict";var{kProxy,kClose,kDestroy,kInterceptors}=require_symbols();var{URL:URL3}=require("url");var Agent=require_agent2();var Pool=require_pool4();var DispatcherBase=require_dispatcher_base();var{InvalidArgumentError,RequestAbortedError}=require_errors5();var buildConnector=require_connect();var kAgent=Symbol("proxy agent");var kClient=Symbol("proxy client");var kProxyHeaders=Symbol("proxy headers");var kRequestTls=Symbol("request tls settings");var kProxyTls=Symbol("proxy tls settings");var kConnectEndpoint=Symbol("connect endpoint function");function defaultProtocolPort(protocol){return protocol==="https:"?443:80}function buildProxyOptions(opts){if(typeof opts==="string"){opts={uri:opts}}if(!opts||!opts.uri){throw new InvalidArgumentError("Proxy opts.uri is mandatory")}return{uri:opts.uri,protocol:opts.protocol||"https"}}function defaultFactory(origin,opts){return new Pool(origin,opts)}var ProxyAgent=class extends DispatcherBase{constructor(opts){super(opts);this[kProxy]=buildProxyOptions(opts);this[kAgent]=new Agent(opts);this[kInterceptors]=opts.interceptors&&opts.interceptors.ProxyAgent&&Array.isArray(opts.interceptors.ProxyAgent)?opts.interceptors.ProxyAgent:[];if(typeof opts==="string"){opts={uri:opts}}if(!opts||!opts.uri){throw new InvalidArgumentError("Proxy opts.uri is mandatory")}const{clientFactory=defaultFactory}=opts;if(typeof clientFactory!=="function"){throw new InvalidArgumentError("Proxy opts.clientFactory must be a function.")}this[kRequestTls]=opts.requestTls;this[kProxyTls]=opts.proxyTls;this[kProxyHeaders]=opts.headers||{};const resolvedUrl=new URL3(opts.uri);const{origin,port,host,username,password}=resolvedUrl;if(opts.auth&&opts.token){throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token")}else if(opts.auth){this[kProxyHeaders]["proxy-authorization"]=`Basic ${opts.auth}`}else if(opts.token){this[kProxyHeaders]["proxy-authorization"]=opts.token}else if(username&&password){this[kProxyHeaders]["proxy-authorization"]=`Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString("base64")}`}const connect=buildConnector({...opts.proxyTls});this[kConnectEndpoint]=buildConnector({...opts.requestTls});this[kClient]=clientFactory(resolvedUrl,{connect});this[kAgent]=new Agent({...opts,connect:async(opts2,callback)=>{let requestedHost=opts2.host;if(!opts2.port){requestedHost+=`:${defaultProtocolPort(opts2.protocol)}`}try{const{socket,statusCode}=await this[kClient].connect({origin,port,path:requestedHost,signal:opts2.signal,headers:{...this[kProxyHeaders],host}});if(statusCode!==200){socket.on("error",()=>{}).destroy();callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))}if(opts2.protocol!=="https:"){callback(null,socket);return}let servername;if(this[kRequestTls]){servername=this[kRequestTls].servername}else{servername=opts2.servername}this[kConnectEndpoint]({...opts2,servername,httpSocket:socket},callback)}catch(err){callback(err)}}})}dispatch(opts,handler){const{host}=new URL3(opts.origin);const headers=buildHeaders(opts.headers);throwIfProxyAuthIsSent(headers);return this[kAgent].dispatch({...opts,headers:{...headers,host}},handler)}async[kClose](){await this[kAgent].close();await this[kClient].close()}async[kDestroy](){await this[kAgent].destroy();await this[kClient].destroy()}};function buildHeaders(headers){if(Array.isArray(headers)){const headersPair={};for(let i=0;i<headers.length;i+=2){headersPair[headers[i]]=headers[i+1]}return headersPair}return headers}function throwIfProxyAuthIsSent(headers){const existProxyAuth=headers&&Object.keys(headers).find(key=>key.toLowerCase()==="proxy-authorization");if(existProxyAuth){throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor")}}module2.exports=ProxyAgent}});var require_RetryHandler=__commonJS({"node_modules/undici/lib/handler/RetryHandler.js"(exports2,module2){var
Must be one of: ${allowedExtensions.join(", ")}`)}if(size2&&!ALLOWED_SIZES.includes(size2)){throw new RangeError(`Invalid size provided: ${size2}
Must be one of: ${ALLOWED_SIZES.join(", ")}`)}const url=new import_node_url4.URL(`${this.base}${route}.${extension}`);if(size2){url.searchParams.set("size",String(size2))}return url.toString()}};__name(CDN,"CDN");function isErrorGroupWrapper(error){return Reflect.has(error,"_errors")}__name(isErrorGroupWrapper,"isErrorGroupWrapper");function isErrorResponse(error){return typeof Reflect.get(error,"message")==="string"}__name(isErrorResponse,"isErrorResponse");var DiscordAPIError=class extends Error{constructor(rawError,code,status,method2,url,bodyData){super(DiscordAPIError.getMessage(rawError));this.rawError=rawError;this.code=code;this.status=status;this.method=method2;this.url=url;this.requestBody={files:bodyData.files,json:bodyData.body}}requestBody;get name(){return`${DiscordAPIError.name}[${this.code}]`}static getMessage(error){let flattened="";if("code"in error){if(error.errors){flattened=[...this.flattenDiscordError(error.errors)].join("\n")}return error.message&&flattened?`${error.message}
${flattened}`:error.message||flattened||"Unknown Error"}return error.error_description??"No Description"}static*flattenDiscordError(obj,key=""){if(isErrorResponse(obj)){return yield`${key.length?`${key}[${obj.code}]`:`${obj.code}`}: ${obj.message}`.trim()}for(const[otherKey,val]of Object.entries(obj)){const nextKey=otherKey.startsWith("_")?key:key?Number.isNaN(Number(otherKey))?`${key}.${otherKey}`:`${key}[${otherKey}]`:otherKey;if(typeof val==="string"){yield val}else if(isErrorGroupWrapper(val)){for(const error of val._errors){yield*this.flattenDiscordError(error,nextKey)}}else{yield*this.flattenDiscordError(val,nextKey)}}}};__name(DiscordAPIError,"DiscordAPIError");var import_node_http4=require("http");var HTTPError2=class extends Error{constructor(status,method2,url,bodyData){super(import_node_http4.STATUS_CODES[status]);this.status=status;this.method=method2;this.url=url;this.requestBody={files:bodyData.files,json:bodyData.body}}requestBody;name=HTTPError2.name};__name(HTTPError2,"HTTPError");var RateLimitError=class extends Error{timeToReset;limit;method;hash;url;route;majorParameter;global;constructor({timeToReset,limit,method:method2,hash,url,route,majorParameter,global:global2}){super();this.timeToReset=timeToReset;this.limit=limit;this.method=method2;this.hash=hash;this.url=url;this.route=route;this.majorParameter=majorParameter;this.global=global2}get name(){return`${RateLimitError.name}[${this.route}]`}};__name(RateLimitError,"RateLimitError");var import_node_buffer22=require("buffer");var import_node_events3=require("events");var import_node_timers2=require("timers");var import_collection2=require_dist();var import_util9=require_dist2();var import_snowflake=require_cjs2();var import_undici4=require_undici();var import_promises25=require("timers/promises");var import_node_buffer5=require("buffer");var import_node_url22=require("url");var import_node_util6=require("util");var import_undici2=require_undici();function parseHeader(header2){if(header2===void 0||typeof header2==="string"){return header2}return header2.join(";")}__name(parseHeader,"parseHeader");function serializeSearchParam(value){switch(typeof value){case"string":return value;case"number":case"bigint":case"boolean":return value.toString();case"object":if(value===null)return null;if(value instanceof Date){return Number.isNaN(value.getTime())?null:value.toISOString()}if(typeof value.toString==="function"&&value.toString!==Object.prototype.toString)return value.toString();return null;default:return null}}__name(serializeSearchParam,"serializeSearchParam");function makeURLSearchParams2(options){const params=new import_node_url22.URLSearchParams;if(!options)return params;for(const[key,value]of Object.entries(options)){const serialized=serializeSearchParam(value);if(serialized!==null)params.append(key,serialized)}return params}__name(makeURLSearchParams2,"makeURLSearchParams");async function parseResponse(res){const header2=parseHeader(res.headers["content-type"]);if(header2==null?void 0:header2.startsWith("application/json")){return res.body.json()}return res.body.arrayBuffer()}__name(parseResponse,"parseResponse");function hasSublimit(bucketRoute,body,method2){if(bucketRoute==="/channels/:id"){if(typeof body!=="object"||body===null)return false;if(method2!=="PATCH")return false;const castedBody=body;return["name","topic"].some(key=>Reflect.has(castedBody,key))}return true}__name(hasSublimit,"hasSublimit");async function resolveBody(body){if(body==null){return null}else if(typeof body==="string"){return body}else if(import_node_util6.types.isUint8Array(body)){return body}else if(import_node_util6.types.isArrayBuffer(body)){return new Uint8Array(body)}else if(body instanceof import_node_url22.URLSearchParams){return body.toString()}else if(body instanceof DataView){return new Uint8Array(body.buffer)}else if(body instanceof import_node_buffer5.Blob){return new Uint8Array(await body.arrayBuffer())}else if(body instanceof import_undici2.FormData){return body}else if(body[Symbol.iterator]){const chunks=[...body];const length=chunks.reduce((a,b)=>a+b.length
${this.stack.slice(this.stack.indexOf("\n"))}`}};__name(_BaseError,"BaseError");var BaseError=_BaseError;var _BaseConstraintError=class _BaseConstraintError extends BaseError{constructor(constraint,message3,given){super(message3);this.constraint=constraint;this.given=given}toJSON(){return{name:this.name,constraint:this.constraint,given:this.given,message:this.message}}};__name(_BaseConstraintError,"BaseConstraintError");var BaseConstraintError=_BaseConstraintError;var _ExpectedConstraintError=class _ExpectedConstraintError extends BaseConstraintError{constructor(constraint,message3,given,expected){super(constraint,message3,given);this.expected=expected}toJSON(){return{name:this.name,constraint:this.constraint,given:this.given,expected:this.expected,message:this.message}}[customInspectSymbolStackLess](depth,options){const constraint=options.stylize(this.constraint,"string");if(depth<0){return options.stylize(`[ExpectedConstraintError: ${constraint}]`,"special")}const newOptions={...options,depth:options.depth===null?null:options.depth-1};const padding=`
${options.stylize("|","undefined")} `;const given=inspect22(this.given,newOptions).replace(/\n/g,padding);const header2=`${options.stylize("ExpectedConstraintError","special")} > ${constraint}`;const message3=options.stylize(this.message,"regexp");const expectedBlock=`
${options.stylize("Expected: ","string")}${options.stylize(this.expected,"boolean")}`;const givenBlock=`
${options.stylize("Received:","regexp")}${padding}${given}`;return`${header2}
${message3}
${expectedBlock}
${givenBlock}`}};__name(_ExpectedConstraintError,"ExpectedConstraintError");var ExpectedConstraintError=_ExpectedConstraintError;var _Result=class _Result2{constructor(success,value,error){this.success=success;if(success){this.value=value}else{this.error=error}}isOk(){return this.success}isErr(){return!this.success}unwrap(){if(this.isOk())return this.value;throw this.error}static ok(value){return new _Result2(true,value)}static err(error){return new _Result2(false,void 0,error)}};__name(_Result,"Result");var Result=_Result;function whenConstraint(key,options,validator,validatorOptions){return{run(input,parent2){if(!parent2){return Result.err(new ExpectedConstraintError("s.object(T.when)",(validatorOptions==null?void 0:validatorOptions.message)??"Validator has no parent",parent2,"Validator to have a parent"))}const isKeyArray=Array.isArray(key);const value=isKeyArray?key.map(k2=>get__default.default(parent2,k2)):get__default.default(parent2,key);const predicate=resolveBooleanIs(options,value,isKeyArray)?options.then:options.otherwise;if(predicate){return predicate(validator).run(input)}return Result.ok(input)}}}__name(whenConstraint,"whenConstraint");function resolveBooleanIs(options,value,isKeyArray){if(options.is===void 0){return isKeyArray?!value.some(val=>!val):Boolean(value)}if(typeof options.is==="function"){return options.is(value)}return value===options.is}__name(resolveBooleanIs,"resolveBooleanIs");var validationEnabled=true;function setGlobalValidationEnabled(enabled3){validationEnabled=enabled3}__name(setGlobalValidationEnabled,"setGlobalValidationEnabled");function getGlobalValidationEnabled(){return validationEnabled}__name(getGlobalValidationEnabled,"getGlobalValidationEnabled");function getValue2(valueOrFn){return typeof valueOrFn==="function"?valueOrFn():valueOrFn}__name(getValue2,"getValue");var _BaseValidator=class _BaseValidator{constructor(validatorOptions={},constraints=[]){this.constraints=[];this.isValidationEnabled=null;this.constraints=constraints;this.validatorOptions=validatorOptions}setParent(parent2){this.parent=parent2;return this}optional(options=this.validatorOptions){return new UnionValidator([new LiteralValidator(void 0,options),this.clone()],options)}nullable(options=this.validatorOptions){return new UnionValidator([new LiteralValidator(null,options),this.clone()],options)}nullish(options=this.validatorOptions){return new UnionValidator([new NullishValidator(options),this.clone()],options)}array(options=this.validatorOptions){return new ArrayValidator(this.clone(),options)}set(options=this.validatorOptions){return new SetValidator(this.clone(),options)}or(...predicates){return new UnionValidator([this.clone(),...predicates],this.validatorOptions)}transform(cb,options=this.validatorOptions){return this.addConstraint({run:input=>Result.ok(cb(input))},options)}reshape(cb,options=this.validatorOptions){return this.addConstraint({run:cb},options)}default(value,options=this.validatorOptions){return new DefaultValidator(this.clone(),value,options)}when(key,options,validatorOptions){return this.addConstraint(whenConstraint(key,options,this,validatorOptions))}describe(description){const clone2=this.clone();clone2.description=description;return clone2}run(value){let result2=this.handle(value);if(result2.isErr())return result2;for(const constraint of this.constraints){result2=constraint.run(result2.value,this.parent);if(result2.isErr())break}return result2}parse(value){if(!this.shouldRunConstraints){return this.handle(value).unwrap()}return this.constraints.reduce((v2,constraint)=>constraint.run(v2).unwrap(),this.handle(value).unwrap())}is(value){return this.run(value).isOk()}setValidationEnabled(isValidationEnabled){const clone2=this.clone();clone2.isValidationEnabled=isValidationEnabled;return clone2}getValidationEnabled(){return getValue2(this.isValidationEnabled)}get shouldRunConstraints(){return getValue2(this.isValidationEnabled)??getGlobalValidationEnabled()}clone(){const clone2=Reflect.construct(this.constructor,[this.validatorOptions,this.constraints]);clone2.isValidationEnabled=this.isVa
${options.stylize("|","undefined")} `;const header2=`${options.stylize("CombinedPropertyError","special")} (${options.stylize(this.errors.length.toString(),"number")})`;const message3=options.stylize(this.message,"regexp");const errors2=this.errors.map(([key,error])=>{const property2=_CombinedPropertyError2.formatProperty(key,options);const body=error[customInspectSymbolStackLess](depth-1,newOptions).replace(/\n/g,padding);return` input${property2}${padding}${body}`}).join("\n\n");return`${header2}
${message3}
${errors2}`}static formatProperty(key,options){if(typeof key==="string")return options.stylize(`.${key}`,"symbol");if(typeof key==="number")return`[${options.stylize(key.toString(),"number")}]`;return`[${options.stylize("Symbol","symbol")}(${key.description})]`}};__name(_CombinedPropertyError,"CombinedPropertyError");var CombinedPropertyError=_CombinedPropertyError;var _ValidationError=class _ValidationError extends BaseError{constructor(validator,message3,given){super(message3);this.validator=validator;this.given=given}toJSON(){return{name:this.name,message:"Unknown validation error occurred.",validator:this.validator,given:this.given}}[customInspectSymbolStackLess](depth,options){const validator=options.stylize(this.validator,"string");if(depth<0){return options.stylize(`[ValidationError: ${validator}]`,"special")}const newOptions={...options,depth:options.depth===null?null:options.depth-1,compact:true};const padding=`
${options.stylize("|","undefined")} `;const given=inspect22(this.given,newOptions).replace(/\n/g,padding);const header2=`${options.stylize("ValidationError","special")} > ${validator}`;const message3=options.stylize(this.message,"regexp");const givenBlock=`
${options.stylize("Received:","regexp")}${padding}${given}`;return`${header2}
${message3}
${givenBlock}`}};__name(_ValidationError,"ValidationError");var ValidationError2=_ValidationError;var _ArrayValidator=class _ArrayValidator extends BaseValidator{constructor(validator,validatorOptions={},constraints=[]){super(validatorOptions,constraints);this.validator=validator}lengthLessThan(length,options=this.validatorOptions){return this.addConstraint(arrayLengthLessThan(length,options))}lengthLessThanOrEqual(length,options=this.validatorOptions){return this.addConstraint(arrayLengthLessThanOrEqual(length,options))}lengthGreaterThan(length,options=this.validatorOptions){return this.addConstraint(arrayLengthGreaterThan(length,options))}lengthGreaterThanOrEqual(length,options=this.validatorOptions){return this.addConstraint(arrayLengthGreaterThanOrEqual(length,options))}lengthEqual(length,options=this.validatorOptions){return this.addConstraint(arrayLengthEqual(length,options))}lengthNotEqual(length,options=this.validatorOptions){return this.addConstraint(arrayLengthNotEqual(length,options))}lengthRange(start,endBefore,options=this.validatorOptions){return this.addConstraint(arrayLengthRange(start,endBefore,options))}lengthRangeInclusive(startAt,endAt,options=this.validatorOptions){return this.addConstraint(arrayLengthRangeInclusive(startAt,endAt,options))}lengthRangeExclusive(startAfter,endBefore,options=this.validatorOptions){return this.addConstraint(arrayLengthRangeExclusive(startAfter,endBefore,options))}unique(options=this.validatorOptions){return this.addConstraint(uniqueArray(options))}clone(){return Reflect.construct(this.constructor,[this.validator,this.validatorOptions,this.constraints])}handle(values2){if(!Array.isArray(values2)){return Result.err(new ValidationError2("s.array(T)",this.validatorOptions.message??"Expected an array",values2))}if(!this.shouldRunConstraints){return Result.ok(values2)}const errors2=[];const transformed=[];for(let i3=0;i3<values2.length;i3++){const result2=this.validator.run(values2[i3]);if(result2.isOk())transformed.push(result2.value);else errors2.push([i3,result2.error])}return errors2.length===0?Result.ok(transformed):Result.err(new CombinedPropertyError(errors2,this.validatorOptions))}};__name(_ArrayValidator,"ArrayValidator");var ArrayValidator=_ArrayValidator;function bigintComparator(comparator,name,expected,number2,options){return{run(input){return comparator(input,number2)?Result.ok(input):Result.err(new ExpectedConstraintError(name,(options==null?void 0:options.message)??"Invalid bigint value",input,expected))}}}__name(bigintComparator,"bigintComparator");function bigintLessThan(value,options){const expected=`expected < ${value}n`;return bigintComparator(lessThan,"s.bigint().lessThan()",expected,value,options)}__name(bigintLessThan,"bigintLessThan");function bigintLessThanOrEqual(value,options){const expected=`expected <= ${value}n`;return bigintComparator(lessThanOrEqual,"s.bigint().lessThanOrEqual()",expected,value,options)}__name(bigintLessThanOrEqual,"bigintLessThanOrEqual");function bigintGreaterThan(value,options){const expected=`expected > ${value}n`;return bigintComparator(greaterThan,"s.bigint().greaterThan()",expected,value,options)}__name(bigintGreaterThan,"bigintGreaterThan");function bigintGreaterThanOrEqual(value,options){const expected=`expected >= ${value}n`;return bigintComparator(greaterThanOrEqual,"s.bigint().greaterThanOrEqual()",expected,value,options)}__name(bigintGreaterThanOrEqual,"bigintGreaterThanOrEqual");function bigintEqual(value,options){const expected=`expected === ${value}n`;return bigintComparator(equal,"s.bigint().equal()",expected,value,options)}__name(bigintEqual,"bigintEqual");function bigintNotEqual(value,options){const expected=`expected !== ${value}n`;return bigintComparator(notEqual,"s.bigint().notEqual()",expected,value,options)}__name(bigintNotEqual,"bigintNotEqual");function bigintDivisibleBy(divider,options){const expected=`expected % ${divider}n === 0n`;return{run(input){return input%divider===0n?Result.ok(input):Result.err(new ExpectedConstraintError("s.bigint().divisibleBy()",(options==null?void 0:options.message)??"Bi
${options.stylize("|","undefined")} `;const expected=inspect22(this.expected,newOptions).replace(/\n/g,padding);const given=inspect22(this.given,newOptions).replace(/\n/g,padding);const header2=`${options.stylize("ExpectedValidationError","special")} > ${validator}`;const message3=options.stylize(this.message,"regexp");const expectedBlock=`
${options.stylize("Expected:","string")}${padding}${expected}`;const givenBlock=`
${options.stylize("Received:","regexp")}${padding}${given}`;return`${header2}
${message3}
${expectedBlock}
${givenBlock}`}};__name(_ExpectedValidationError,"ExpectedValidationError");var ExpectedValidationError=_ExpectedValidationError;var _InstanceValidator=class _InstanceValidator extends BaseValidator{constructor(expected,validatorOptions={},constraints=[]){super(validatorOptions,constraints);this.expected=expected}handle(value){return value instanceof this.expected?Result.ok(value):Result.err(new ExpectedValidationError("s.instance(V)",this.validatorOptions.message??"Expected",value,this.expected))}clone(){return Reflect.construct(this.constructor,[this.expected,this.validatorOptions,this.constraints])}};__name(_InstanceValidator,"InstanceValidator");var InstanceValidator=_InstanceValidator;var _LiteralValidator=class _LiteralValidator extends BaseValidator{constructor(literal,validatorOptions={},constraints=[]){super(validatorOptions,constraints);this.expected=literal}handle(value){return Object.is(value,this.expected)?Result.ok(value):Result.err(new ExpectedValidationError("s.literal(V)",this.validatorOptions.message??"Expected values to be equals",value,this.expected))}clone(){return Reflect.construct(this.constructor,[this.expected,this.validatorOptions,this.constraints])}};__name(_LiteralValidator,"LiteralValidator");var LiteralValidator=_LiteralValidator;var _NeverValidator=class _NeverValidator extends BaseValidator{handle(value){return Result.err(new ValidationError2("s.never()",this.validatorOptions.message??"Expected a value to not be passed",value))}};__name(_NeverValidator,"NeverValidator");var NeverValidator=_NeverValidator;var _NullishValidator=class _NullishValidator extends BaseValidator{handle(value){return value===void 0||value===null?Result.ok(value):Result.err(new ValidationError2("s.nullish()",this.validatorOptions.message??"Expected undefined or null",value))}};__name(_NullishValidator,"NullishValidator");var NullishValidator=_NullishValidator;function numberComparator(comparator,name,expected,number2,options){return{run(input){return comparator(input,number2)?Result.ok(input):Result.err(new ExpectedConstraintError(name,(options==null?void 0:options.message)??"Invalid number value",input,expected))}}}__name(numberComparator,"numberComparator");function numberLessThan(value,options){const expected=`expected < ${value}`;return numberComparator(lessThan,"s.number().lessThan()",expected,value,options)}__name(numberLessThan,"numberLessThan");function numberLessThanOrEqual(value,options){const expected=`expected <= ${value}`;return numberComparator(lessThanOrEqual,"s.number().lessThanOrEqual()",expected,value,options)}__name(numberLessThanOrEqual,"numberLessThanOrEqual");function numberGreaterThan(value,options){const expected=`expected > ${value}`;return numberComparator(greaterThan,"s.number().greaterThan()",expected,value,options)}__name(numberGreaterThan,"numberGreaterThan");function numberGreaterThanOrEqual(value,options){const expected=`expected >= ${value}`;return numberComparator(greaterThanOrEqual,"s.number().greaterThanOrEqual()",expected,value,options)}__name(numberGreaterThanOrEqual,"numberGreaterThanOrEqual");function numberEqual(value,options){const expected=`expected === ${value}`;return numberComparator(equal,"s.number().equal()",expected,value,options)}__name(numberEqual,"numberEqual");function numberNotEqual(value,options){const expected=`expected !== ${value}`;return numberComparator(notEqual,"s.number().notEqual()",expected,value,options)}__name(numberNotEqual,"numberNotEqual");function numberInt(options){return{run(input){return Number.isInteger(input)?Result.ok(input):Result.err(new ExpectedConstraintError("s.number().int()",(options==null?void 0:options.message)??"Given value is not an integer",input,"Number.isInteger(expected) to be true"))}}}__name(numberInt,"numberInt");function numberSafeInt(options){return{run(input){return Number.isSafeInteger(input)?Result.ok(input):Result.err(new ExpectedConstraintError("s.number().safeInt()",(options==null?void 0:options.message)??"Given value is not a safe integer",input,"Number.isSafeInteger(expected) to be true"))}}}__name(numberSafeInt,
${message3}`}};__name(_MissingPropertyError,"MissingPropertyError");var MissingPropertyError=_MissingPropertyError;var _UnknownPropertyError=class _UnknownPropertyError extends BaseError{constructor(property2,value,options){super((options==null?void 0:options.message)??"Received unexpected property");this.property=property2;this.value=value}toJSON(){return{name:this.name,message:this.message,property:this.property,value:this.value}}[customInspectSymbolStackLess](depth,options){const property2=options.stylize(this.property.toString(),"string");if(depth<0){return options.stylize(`[UnknownPropertyError: ${property2}]`,"special")}const newOptions={...options,depth:options.depth===null?null:options.depth-1,compact:true};const padding=`
${options.stylize("|","undefined")} `;const given=inspect22(this.value,newOptions).replace(/\n/g,padding);const header2=`${options.stylize("UnknownPropertyError","special")} > ${property2}`;const message3=options.stylize(this.message,"regexp");const givenBlock=`
${options.stylize("Received:","regexp")}${padding}${given}`;return`${header2}
${message3}
${givenBlock}`}};__name(_UnknownPropertyError,"UnknownPropertyError");var UnknownPropertyError=_UnknownPropertyError;var _DefaultValidator=class _DefaultValidator extends BaseValidator{constructor(validator,value,validatorOptions={},constraints=[]){super(validatorOptions,constraints);this.validator=validator;this.defaultValue=value}default(value,options=this.validatorOptions){const clone2=this.clone();clone2.validatorOptions=options;clone2.defaultValue=value;return clone2}handle(value){return typeof value==="undefined"?Result.ok(getValue2(this.defaultValue)):this.validator["handle"](value)}clone(){return Reflect.construct(this.constructor,[this.validator,this.defaultValue,this.validatorOptions,this.constraints])}};__name(_DefaultValidator,"DefaultValidator");var DefaultValidator=_DefaultValidator;var _CombinedError=class _CombinedError extends BaseError{constructor(errors2,validatorOptions){super((validatorOptions==null?void 0:validatorOptions.message)??"Received one or more errors");this.errors=errors2}[customInspectSymbolStackLess](depth,options){if(depth<0){return options.stylize("[CombinedError]","special")}const newOptions={...options,depth:options.depth===null?null:options.depth-1,compact:true};const padding=`
${options.stylize("|","undefined")} `;const header2=`${options.stylize("CombinedError","special")} (${options.stylize(this.errors.length.toString(),"number")})`;const message3=options.stylize(this.message,"regexp");const errors2=this.errors.map((error,i3)=>{const index=options.stylize((i3+1).toString(),"number");const body=error[customInspectSymbolStackLess](depth-1,newOptions).replace(/\n/g,padding);return` ${index} ${body}`}).join("\n\n");return`${header2}
${message3}
${errors2}`}};__name(_CombinedError,"CombinedError");var CombinedError=_CombinedError;var _UnionValidator=class _UnionValidator2 extends BaseValidator{constructor(validators,validatorOptions,constraints=[]){super(validatorOptions,constraints);this.validators=validators}optional(options=this.validatorOptions){if(this.validators.length===0)return new _UnionValidator2([new LiteralValidator(void 0,options)],this.validatorOptions,this.constraints);const[validator]=this.validators;if(validator instanceof LiteralValidator){if(validator.expected===void 0)return this.clone();if(validator.expected===null){return new _UnionValidator2([new NullishValidator(options),...this.validators.slice(1)],this.validatorOptions,this.constraints)}}else if(validator instanceof NullishValidator){return this.clone()}return new _UnionValidator2([new LiteralValidator(void 0,options),...this.validators],this.validatorOptions)}required(options=this.validatorOptions){if(this.validators.length===0)return this.clone();const[validator]=this.validators;if(validator instanceof LiteralValidator){if(validator.expected===void 0){return new _UnionValidator2(this.validators.slice(1),this.validatorOptions,this.constraints)}}else if(validator instanceof NullishValidator){return new _UnionValidator2([new LiteralValidator(null,options),...this.validators.slice(1)],this.validatorOptions,this.constraints)}return this.clone()}nullable(options=this.validatorOptions){if(this.validators.length===0){return new _UnionValidator2([new LiteralValidator(null,options)],this.validatorOptions,this.constraints)}const[validator]=this.validators;if(validator instanceof LiteralValidator){if(validator.expected===null)return this.clone();if(validator.expected===void 0){return new _UnionValidator2([new NullishValidator(options),...this.validators.slice(1)],this.validatorOptions,this.constraints)}}else if(validator instanceof NullishValidator){return this.clone()}return new _UnionValidator2([new LiteralValidator(null,options),...this.validators],this.validatorOptions)}nullish(options=this.validatorOptions){if(this.validators.length===0){return new _UnionValidator2([new NullishValidator(options)],options,this.constraints)}const[validator]=this.validators;if(validator instanceof LiteralValidator){if(validator.expected===null||validator.expected===void 0){return new _UnionValidator2([new NullishValidator(options),...this.validators.slice(1)],options,this.constraints)}}else if(validator instanceof NullishValidator){return this.clone()}return new _UnionValidator2([new NullishValidator(options),...this.validators],options)}or(...predicates){return new _UnionValidator2([...this.validators,...predicates],this.validatorOptions)}clone(){return Reflect.construct(this.constructor,[this.validators,this.validatorOptions,this.constraints])}handle(value){const errors2=[];for(const validator of this.validators){const result2=validator.run(value);if(result2.isOk())return result2;errors2.push(result2.error)}return Result.err(new CombinedError(errors2,this.validatorOptions))}};__name(_UnionValidator,"UnionValidator");var UnionValidator=_UnionValidator;var _ObjectValidator=class _ObjectValidator2 extends BaseValidator{constructor(shape,strategy=0,validatorOptions={},constraints=[]){super(validatorOptions,constraints);this.keys=[];this.requiredKeys=new Map;this.possiblyUndefinedKeys=new Map;this.possiblyUndefinedKeysWithDefaults=new Map;this.shape=shape;this.strategy=strategy;switch(this.strategy){case 0:this.handleStrategy=value=>this.handleIgnoreStrategy(value);break;case 1:{this.handleStrategy=value=>this.handleStrictStrategy(value);break}case 2:this.handleStrategy=value=>this.handlePassthroughStrategy(value);break}const shapeEntries=Object.entries(shape);this.keys=shapeEntries.map(([key])=>key);for(const[key,validator]of shapeEntries){if(validator instanceof UnionValidator){const[possiblyLiteralOrNullishPredicate]=validator["validators"];if(possiblyLiteralOrNullishPredicate instanceof NullishValidator){this.possiblyUndefinedKeys.set(key,validator)}else if(possiblyLiteralOrNullishPredicate instanceof Literal
${verticalLine} `;const given=inspect22(this.given,newOptions).replace(/\n/g,padding);const header2=`${options.stylize("MultiplePossibilitiesConstraintError","special")} > ${constraint}`;const message3=options.stylize(this.message,"regexp");const expectedPadding=`
${verticalLine} - `;const expectedBlock=`
${options.stylize("Expected any of the following:","string")}${expectedPadding}${this.expected.map(possible=>options.stylize(possible,"boolean")).join(expectedPadding)}`;const givenBlock=`
${options.stylize("Received:","regexp")}${padding}${given}`;return`${header2}
${message3}
${expectedBlock}
${givenBlock}`}};__name(_MultiplePossibilitiesConstraintError,"MultiplePossibilitiesConstraintError");var MultiplePossibilitiesConstraintError=_MultiplePossibilitiesConstraintError;function combinedErrorFn(...fns){switch(fns.length){case 0:return()=>null;case 1:return fns[0];case 2:{const[fn0,fn1]=fns;return(...params)=>fn0(...params)||fn1(...params)}default:{return(...params)=>{for(const fn2 of fns){const result2=fn2(...params);if(result2)return result2}return null}}}}__name(combinedErrorFn,"combinedErrorFn");function createUrlValidators(options,validatorOptions){var _a13,_b2;const fns=[];if((_a13=options==null?void 0:options.allowedProtocols)==null?void 0:_a13.length)fns.push(allowedProtocolsFn(options.allowedProtocols,validatorOptions));if((_b2=options==null?void 0:options.allowedDomains)==null?void 0:_b2.length)fns.push(allowedDomainsFn(options.allowedDomains,validatorOptions));return combinedErrorFn(...fns)}__name(createUrlValidators,"createUrlValidators");function allowedProtocolsFn(allowedProtocols,options){return(input,url)=>allowedProtocols.includes(url.protocol)?null:new MultiplePossibilitiesConstraintError("s.string().url()",(options==null?void 0:options.message)??"Invalid URL protocol",input,allowedProtocols)}__name(allowedProtocolsFn,"allowedProtocolsFn");function allowedDomainsFn(allowedDomains,options){return(input,url)=>allowedDomains.includes(url.hostname)?null:new MultiplePossibilitiesConstraintError("s.string().url()",(options==null?void 0:options.message)??"Invalid URL domain",input,allowedDomains)}__name(allowedDomainsFn,"allowedDomainsFn");function stringLengthComparator(comparator,name,expected,length,options){return{run(input){return comparator(input.length,length)?Result.ok(input):Result.err(new ExpectedConstraintError(name,(options==null?void 0:options.message)??"Invalid string length",input,expected))}}}__name(stringLengthComparator,"stringLengthComparator");function stringLengthLessThan(length,options){const expected=`expected.length < ${length}`;return stringLengthComparator(lessThan,"s.string().lengthLessThan()",expected,length,options)}__name(stringLengthLessThan,"stringLengthLessThan");function stringLengthLessThanOrEqual(length,options){const expected=`expected.length <= ${length}`;return stringLengthComparator(lessThanOrEqual,"s.string().lengthLessThanOrEqual()",expected,length,options)}__name(stringLengthLessThanOrEqual,"stringLengthLessThanOrEqual");function stringLengthGreaterThan(length,options){const expected=`expected.length > ${length}`;return stringLengthComparator(greaterThan,"s.string().lengthGreaterThan()",expected,length,options)}__name(stringLengthGreaterThan,"stringLengthGreaterThan");function stringLengthGreaterThanOrEqual(length,options){const expected=`expected.length >= ${length}`;return stringLengthComparator(greaterThanOrEqual,"s.string().lengthGreaterThanOrEqual()",expected,length,options)}__name(stringLengthGreaterThanOrEqual,"stringLengthGreaterThanOrEqual");function stringLengthEqual(length,options){const expected=`expected.length === ${length}`;return stringLengthComparator(equal,"s.string().lengthEqual()",expected,length,options)}__name(stringLengthEqual,"stringLengthEqual");function stringLengthNotEqual(length,options){const expected=`expected.length !== ${length}`;return stringLengthComparator(notEqual,"s.string().lengthNotEqual()",expected,length,options)}__name(stringLengthNotEqual,"stringLengthNotEqual");function stringEmail(options){return{run(input){return validateEmail(input)?Result.ok(input):Result.err(new ExpectedConstraintError("s.string().email()",(options==null?void 0:options.message)??"Invalid email address",input,"expected to be an email address"))}}}__name(stringEmail,"stringEmail");function stringRegexValidator(type2,expected,regex3,options){return{run(input){return regex3.test(input)?Result.ok(input):Result.err(new ExpectedConstraintError(type2,(options==null?void 0:options.message)??"Invalid string format",input,expected))}}}__name(stringRegexValidator,"stringRegexValidator");function stringUrl(options,validatorOptions){const validatorFn=crea
${options.stylize("|","undefined")} `;const pairs2=this.enumKeys.map(key=>{const enumValue=this.enumMappings.get(key);return`${options.stylize(key,"string")} or ${options.stylize(enumValue.toString(),typeof enumValue==="number"?"number":"string")}`}).join(padding);const header2=`${options.stylize("UnknownEnumValueError","special")} > ${value}`;const message3=options.stylize(this.message,"regexp");const pairsBlock=`${padding}${pairs2}`;return`${header2}
${message3}
${pairsBlock}`}};__name(_UnknownEnumValueError,"UnknownEnumValueError");var UnknownEnumValueError=_UnknownEnumValueError;var _NativeEnumValidator=class _NativeEnumValidator extends BaseValidator{constructor(enumShape,validatorOptions={}){super(validatorOptions);this.hasNumericElements=false;this.enumMapping=new Map;this.enumShape=enumShape;this.enumKeys=Object.keys(enumShape).filter(key=>{return typeof enumShape[enumShape[key]]!=="number"});for(const key of this.enumKeys){const enumValue=enumShape[key];this.enumMapping.set(key,enumValue);this.enumMapping.set(enumValue,enumValue);if(typeof enumValue==="number"){this.hasNumericElements=true;this.enumMapping.set(`${enumValue}`,enumValue)}}}handle(value){const typeOfValue=typeof value;if(typeOfValue==="number"){if(!this.hasNumericElements){return Result.err(new ValidationError2("s.nativeEnum(T)",this.validatorOptions.message??"Expected the value to be a string",value))}}else if(typeOfValue!=="string"){return Result.err(new ValidationError2("s.nativeEnum(T)",this.validatorOptions.message??"Expected the value to be a string or number",value))}const casted=value;const possibleEnumValue=this.enumMapping.get(casted);return typeof possibleEnumValue==="undefined"?Result.err(new UnknownEnumValueError(casted,this.enumKeys,this.enumMapping,this.validatorOptions)):Result.ok(possibleEnumValue)}clone(){return Reflect.construct(this.constructor,[this.enumShape,this.validatorOptions])}};__name(_NativeEnumValidator,"NativeEnumValidator");var NativeEnumValidator=_NativeEnumValidator;function typedArrayByteLengthComparator(comparator,name,expected,length,options){return{run(input){return comparator(input.byteLength,length)?Result.ok(input):Result.err(new ExpectedConstraintError(name,(options==null?void 0:options.message)??"Invalid Typed Array byte length",input,expected))}}}__name(typedArrayByteLengthComparator,"typedArrayByteLengthComparator");function typedArrayByteLengthLessThan(value,options){const expected=`expected.byteLength < ${value}`;return typedArrayByteLengthComparator(lessThan,"s.typedArray(T).byteLengthLessThan()",expected,value,options)}__name(typedArrayByteLengthLessThan,"typedArrayByteLengthLessThan");function typedArrayByteLengthLessThanOrEqual(value,options){const expected=`expected.byteLength <= ${value}`;return typedArrayByteLengthComparator(lessThanOrEqual,"s.typedArray(T).byteLengthLessThanOrEqual()",expected,value,options)}__name(typedArrayByteLengthLessThanOrEqual,"typedArrayByteLengthLessThanOrEqual");function typedArrayByteLengthGreaterThan(value,options){const expected=`expected.byteLength > ${value}`;return typedArrayByteLengthComparator(greaterThan,"s.typedArray(T).byteLengthGreaterThan()",expected,value,options)}__name(typedArrayByteLengthGreaterThan,"typedArrayByteLengthGreaterThan");function typedArrayByteLengthGreaterThanOrEqual(value,options){const expected=`expected.byteLength >= ${value}`;return typedArrayByteLengthComparator(greaterThanOrEqual,"s.typedArray(T).byteLengthGreaterThanOrEqual()",expected,value,options)}__name(typedArrayByteLengthGreaterThanOrEqual,"typedArrayByteLengthGreaterThanOrEqual");function typedArrayByteLengthEqual(value,options){const expected=`expected.byteLength === ${value}`;return typedArrayByteLengthComparator(equal,"s.typedArray(T).byteLengthEqual()",expected,value,options)}__name(typedArrayByteLengthEqual,"typedArrayByteLengthEqual");function typedArrayByteLengthNotEqual(value,options){const expected=`expected.byteLength !== ${value}`;return typedArrayByteLengthComparator(notEqual,"s.typedArray(T).byteLengthNotEqual()",expected,value,options)}__name(typedArrayByteLengthNotEqual,"typedArrayByteLengthNotEqual");function typedArrayByteLengthRange(start,endBefore,options){const expected=`expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`;return{run(input){return input.byteLength>=start&&input.byteLength<endBefore?Result.ok(input):Result.err(new ExpectedConstraintError("s.typedArray(T).byteLengthRange()",(options==null?void 0:options.message)??"Invalid Typed Array byte length",input,expected))}}}__name(typedArr
${language2}
\`\`\``:`\`\`\`${language2}
${content}
\`\`\``}__name(codeBlock,"codeBlock");function inlineCode(content){return`\`${content}\``}__name(inlineCode,"inlineCode");function italic(content){return`_${content}_`}__name(italic,"italic");function bold(content){return`**${content}**`}__name(bold,"bold");function underscore(content){return underline(content)}__name(underscore,"underscore");function underline(content){return`__${content}__`}__name(underline,"underline");function strikethrough(content){return`~~${content}~~`}__name(strikethrough,"strikethrough");function quote(content){return`> ${content}`}__name(quote,"quote");function blockQuote(content){return`>>> ${content}`}__name(blockQuote,"blockQuote");function hideLinkEmbed(url){return`<${url}>`}__name(hideLinkEmbed,"hideLinkEmbed");function hyperlink(content,url,title){return title?`[${content}](${url} "${title}")`:`[${content}](${url})`}__name(hyperlink,"hyperlink");function spoiler(content){return`||${content}||`}__name(spoiler,"spoiler");function userMention(userId){return`<@${userId}>`}__name(userMention,"userMention");function channelMention(channelId){return`<#${channelId}>`}__name(channelMention,"channelMention");function roleMention(roleId){return`<@&${roleId}>`}__name(roleMention,"roleMention");function chatInputApplicationCommandMention(commandName,subcommandGroupName,subcommandName,commandId){if(commandId!==void 0){return`</${commandName} ${subcommandGroupName} ${subcommandName}:${commandId}>`}if(subcommandName!==void 0){return`</${commandName} ${subcommandGroupName}:${subcommandName}>`}return`</${commandName}:${subcommandGroupName}>`}__name(chatInputApplicationCommandMention,"chatInputApplicationCommandMention");function formatEmoji(emojiIdOrOptions,animated){const options=typeof emojiIdOrOptions==="string"?{id:emojiIdOrOptions,animated:animated??false}:emojiIdOrOptions;const{id,animated:isAnimated,name:emojiName}=options;return`<${isAnimated?"a":""}:${emojiName??"_"}:${id}>`}__name(formatEmoji,"formatEmoji");function channelLink(channelId,guildId){return`https://discord.com/channels/${guildId??"@me"}/${channelId}`}__name(channelLink,"channelLink");function messageLink(channelId,messageId,guildId){return`${guildId===void 0?channelLink(channelId):channelLink(channelId,guildId)}/${messageId}`}__name(messageLink,"messageLink");var HeadingLevel=(HeadingLevel2=>{HeadingLevel2[HeadingLevel2["One"]=1]="One";HeadingLevel2[HeadingLevel2["Two"]=2]="Two";HeadingLevel2[HeadingLevel2["Three"]=3]="Three";return HeadingLevel2})(HeadingLevel||{});function heading(content,level){switch(level){case 3:return`### ${content}`;case 2:return`## ${content}`;default:return`# ${content}`}}__name(heading,"heading");function listCallback(element,startNumber,depth=0){if(Array.isArray(element)){return element.map(element2=>listCallback(element2,startNumber,depth+1)).join("\n")}return`${" ".repeat(depth-1)}${startNumber?`${startNumber}.`:"-"} ${element}`}__name(listCallback,"listCallback");function orderedList(list,startNumber=1){return listCallback(list,Math.max(startNumber,1))}__name(orderedList,"orderedList");function unorderedList(list){return listCallback(list)}__name(unorderedList,"unorderedList");function subtext(content){return`-# ${content}`}__name(subtext,"subtext");function time(timeOrSeconds,style){if(typeof timeOrSeconds!=="number"){timeOrSeconds=Math.floor(((timeOrSeconds==null?void 0:timeOrSeconds.getTime())??Date.now())/1e3)}return typeof style==="string"?`<t:${timeOrSeconds}:${style}>`:`<t:${timeOrSeconds}>`}__name(time,"time");function applicationDirectory(applicationId,skuId){const url=`https://discord.com/application-directory/${applicationId}/store`;return skuId?`${url}/${skuId}`:url}__name(applicationDirectory,"applicationDirectory");var TimestampStyles={ShortTime:"t",LongTime:"T",ShortDate:"d",LongDate:"D",ShortDateTime:"f",LongDateTime:"F",RelativeTime:"R"};var Faces=(Faces2=>{Faces2["Shrug"]="¯\\_(ツ)_/¯";Faces2["Tableflip"]="(╯°□°)╯︵ ┻━┻";Faces2["Unflip"]="┬─┬ノ( º _ ºノ)";return Faces2})(Faces||{});var GuildNavigationMentions=(GuildNavigationMentions2=>{GuildNavigationMen
Emitted 'error' event${ctorInfo} at:
`;const errStack=err.stack.split("\n").slice(1);const ownStack=own.stack.split("\n").slice(1);const{0:len,1:off}=identicalSequenceRange(ownStack,errStack);if(len>0){ownStack.splice(off+1,len-2," [... lines matching original stack trace ...]")}return err.stack+sep3+ownStack.join("\n")}__name(enhanceStackTrace,"enhanceStackTrace");var brandSymbol=Symbol.for("async-event-emitter.ts-brand");var _AsyncEventEmitter=class _AsyncEventEmitter2{constructor(){this._events={__proto__:null};this._eventCount=0;this._maxListeners=10;this._internalPromiseMap=new Map;this._wrapperId=0n}addListener(eventName,listener){validateListener(listener);const wrapped=this._wrapListener(eventName,listener,false);this._addListener(eventName,wrapped,false);return this}on(eventName,listener){return this.addListener(eventName,listener)}once(eventName,listener){validateListener(listener);const wrapped=this._wrapListener(eventName,listener,true);this._addListener(eventName,wrapped,false);return this}removeListener(eventName,listener){validateListener(listener);const events=this._events;const eventList=events[eventName];if(eventList===void 0){return this}if(eventList===listener||eventList.listener===listener){if(--this._eventCount===0){this._events={__proto__:null}}else{delete events[eventName];if(events.removeListener){this.emit("removeListener",eventName,eventList.listener??eventList)}}}else if(typeof eventList!=="function"){let position=-1;for(let i=eventList.length-1;i>=0;i--){if(eventList[i]===listener||eventList[i].listener===listener){position=i;break}}if(position<0){return this}if(position===0){eventList.shift()}else{spliceOne(eventList,position)}if(eventList.length===0){delete events[eventName];--this._eventCount}if(events.removeListener!==void 0){this.emit("removeListener",eventName,listener)}}return this}off(eventName,listener){return this.removeListener(eventName,listener)}removeAllListeners(event){const events=this._events;if(events.removeListener===void 0){if(!event){this._events={__proto__:null};this._eventCount=0}else if(events[event]!==void 0){if(--this._eventCount===0){this._events={__proto__:null}}else{delete events[event]}}return this}if(!event){for(const key of Reflect.ownKeys(events)){if(key==="removeListener"){continue}this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={__proto__:null};this._eventCount=0;return this}const listeners=events[event];if(typeof listeners==="function"){this.removeListener(event,listeners)}else if(listeners!==void 0){for(let i=listeners.length-1;i>=0;i--){this.removeListener(event,listeners[i])}}return this}setMaxListeners(n){if(typeof n!=="number"||n<0||Number.isNaN(n)){throw new RangeError(`Expected to get a non-negative number for "setMaxListeners", got ${n} instead`)}this._maxListeners=n;return this}getMaxListeners(){return this._maxListeners}listeners(eventName){const eventList=this._events[eventName];if(eventList===void 0){return[]}if(typeof eventList==="function"){return[eventList.listener??eventList]}const ret=arrayClone(eventList);for(let i=0;i<ret.length;++i){const orig=ret[i].listener;if(typeof orig==="function"){ret[i]=orig}}return ret}rawListeners(eventName){const eventList=this._events[eventName];if(eventList===void 0){return[]}if(typeof eventList==="function"){return[eventList]}return arrayClone(eventList)}emit(eventName,...args2){let doError=eventName==="error";const events=this._events;if(events!==void 0){doError=doError&&events.error===void 0}else if(!doError){return false}if(doError){let er;if(args2.length>0){er=args2[0]}if(er instanceof Error){try{const capture={};Error.captureStackTrace(capture,_AsyncEventEmitter2.prototype.emit);Object.defineProperty(er,"stack",{value:enhanceStackTrace.call(this,er,capture),configurable:true})}catch{}throw er}const stringifiedError=String(er);const err=new Error(`Unhandled 'error' event emitted, received ${stringifiedError}`);err.context=er;throw err}const handlers2=events[eventName];if(handlers2===void 0){return false}if(typeof handlers2==="function"){const result2=handlers2.apply(this,args2);if(result2!==void 0&&r
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message3)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message3){if(server.listenerCount("wsClientError")){const err=new Error(message3);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message3)}}}});var require_ws=__commonJS({"node_modules/ws/index.js"(exports2,module2){"use strict";var WebSocket2=require_websocket2();WebSocket2.createWebSocketStream=require_stream2();WebSocket2.Server=require_websocket_server();WebSocket2.Receiver=require_receiver2();WebSocket2.Sender=require_sender();WebSocket2.WebSocket=WebSocket2;WebSocket2.WebSocketServer=WebSocket2.Server;module2.exports=WebSocket2}});var require_dist8=__commonJS({"node_modules/@discordjs/ws/dist/index.js"(exports2,module2){"use strict";var __create2=Object.create;var __defProp2=Object.defineProperty;var __getOwnPropDesc2=Object.getOwnPropertyDescriptor;var __getOwnPropNames2=Object.getOwnPropertyNames;var __getProtoOf2=Object.getPrototypeOf;var __hasOwnProp2=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __name=(target,value)=>__defProp2(target,"name",{value,configurable:true});var __export2=(target,all2)=>{for(var name in all2)__defProp2(target,name,{get:all2[name],enumerable:true})};var __copyProps2=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames2(from))if(!__hasOwnProp2.call(to,key)&&key!==except)__defProp2(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable})}return to};var __toESM2=(mod3,isNodeMode,target)=>(target=mod3!=null?__create2(__getProtoOf2(mod3)):{},__copyProps2(isNodeMode||!mod3||!mod3.__esModule?__defProp2(target,"default",{value:mod3,enumerable:true}):target,mod3));var __toCommonJS2=mod3=>__copyProps2(__defProp2({},"__esModule",{value:true}),mod3);var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var src_exports2={};__export2(src_exports2,{CloseCodes:()=>CloseCodes,CompressionMethod:()=>CompressionMethod,DefaultDeviceProperty:()=>DefaultDeviceProperty,DefaultWebSocketManagerOptions:()=>DefaultWebSocketManagerOptions,Encoding:()=>Encoding,ImportantGatewayOpcodes:()=>ImportantGatewayOpcodes,SimpleContextFetchingStrategy:()=>SimpleContextFetchingStrategy,SimpleIdentifyThrottler:()=>SimpleIdentifyThrottler,SimpleShardingStrategy:()=>SimpleShardingStrategy,WebSocketManager:()=>WebSocketManager2,WebSocketShard:()=>WebSocketShard,WebSocketShardDestroyRecovery:()=>WebSocketShardDestroyRecovery,WebSocketShardEvents:()=>WebSocketShardEvents,WebSocketShardStatus:()=>WebSocketShardStatus,WorkerBootstrapper:()=>WorkerBootstrapper,WorkerContextFetchingStrategy:()=>WorkerContextFetchingStrategy,WorkerReceivePayloadOp:()=>WorkerReceivePayloadOp,WorkerSendPayloadOp:()=>WorkerSendPayloadOp,WorkerShardingStrategy:()=>WorkerShardingStrategy,getInitialSendRateLimitState:()=>getInitialSendRateLimitState,managerToFetchingStrategyOptions:()=>managerToFetchingStrategyOptions,version:()=>version});module2.exports=__toCommonJS2(src_exports2);async function managerToFetchingStrategyOptions(manager){const{buildIdentifyThrottler,buildStrategy,retrieveSessionInfo,updateSessionInfo,shardCount,shardIds,rest:rest2,...managerOptions}=manager.options;return{...managerOptions,gatewayInformation:await manager.fetchGatewayInformation(),shardCount:await manager.getShardCount()}}__name(managerToFetchingStrategyOptions,"managerToFetchingStrategyOptions");var _SimpleContextFetchingStrategy=class{constructor(manager,options){this.manager=manager;this.options=options}static async ensureThrottler(manager){const throttler=_SimpleContextFetchingStrategy.throttlerCache.get(manager);if(throttler){return throttler}const newThrottler=await manager.options.buildIdentifyThrottler(manager);_SimpleContextFetchingStrategy.thro
${messages.slice(1).map(m=>` ${m}`).join("\n")}`:""}`;this.emit("debug",{message:message3})}};__name(WebSocketShard,"WebSocketShard");var SimpleShardingStrategy=class{manager;shards=new import_collection6.Collection;constructor(manager){this.manager=manager}async spawn(shardIds){const strategyOptions=await managerToFetchingStrategyOptions(this.manager);for(const shardId of shardIds){const strategy=new SimpleContextFetchingStrategy(this.manager,strategyOptions);const shard=new WebSocketShard(strategy,shardId);for(const event of Object.values(WebSocketShardEvents)){shard.on(event,payload=>this.manager.emit(event,{...payload,shardId}))}this.shards.set(shardId,shard)}}async connect(){const promises=[];for(const shard of this.shards.values()){promises.push(shard.connect())}await Promise.all(promises)}async destroy(options){const promises=[];for(const shard of this.shards.values()){promises.push(shard.destroy(options))}await Promise.all(promises);this.shards.clear()}async send(shardId,payload){const shard=this.shards.get(shardId);if(!shard){throw new RangeError(`Shard ${shardId} not found`)}return shard.send(payload)}async fetchStatus(){return this.shards.mapValues(shard=>shard.status)}};__name(SimpleShardingStrategy,"SimpleShardingStrategy");var import_node_worker_threads3=require("worker_threads");var import_collection7=require_dist();var WorkerBootstrapper=class{data=import_node_worker_threads3.workerData;shards=new import_collection7.Collection;constructor(){if(import_node_worker_threads3.isMainThread){throw new Error("Expected WorkerBootstrap to not be used within the main thread")}}async connect(shardId){const shard=this.shards.get(shardId);if(!shard){throw new RangeError(`Shard ${shardId} does not exist`)}await shard.connect()}async destroy(shardId,options){const shard=this.shards.get(shardId);if(!shard){throw new RangeError(`Shard ${shardId} does not exist`)}await shard.destroy(options)}setupThreadEvents(){import_node_worker_threads3.parentPort.on("messageerror",err=>{throw err}).on("message",async payload=>{switch(payload.op){case 0:{await this.connect(payload.shardId);const response={op:0,shardId:payload.shardId};import_node_worker_threads3.parentPort.postMessage(response);break}case 1:{await this.destroy(payload.shardId,payload.options);const response={op:1,shardId:payload.shardId};import_node_worker_threads3.parentPort.postMessage(response);break}case 2:{const shard=this.shards.get(payload.shardId);if(!shard){throw new RangeError(`Shard ${payload.shardId} does not exist`)}await shard.send(payload.payload);break}case 3:{break}case 4:{break}case 5:{const shard=this.shards.get(payload.shardId);if(!shard){throw new Error(`Shard ${payload.shardId} does not exist`)}const response={op:6,status:shard.status,nonce:payload.nonce};import_node_worker_threads3.parentPort.postMessage(response);break}}})}async bootstrap(options={}){var _a13;for(const shardId of this.data.shardIds){const shard=new WebSocketShard(new WorkerContextFetchingStrategy(this.data),shardId);for(const event of options.forwardEvents??Object.values(WebSocketShardEvents)){shard.on(event,data=>{const payload={op:2,event,data,shardId};import_node_worker_threads3.parentPort.postMessage(payload)})}await((_a13=options.shardCallback)==null?void 0:_a13.call(options,shard));this.shards.set(shardId,shard)}this.setupThreadEvents();const message3={op:7};import_node_worker_threads3.parentPort.postMessage(message3)}};__name(WorkerBootstrapper,"WorkerBootstrapper");var import_util32=require_dist2();var import_async_event_emitter2=require_dist7();var import_v103=require_v106();var WebSocketManager2=class extends import_async_event_emitter2.AsyncEventEmitter{options;gatewayInformation=null;shardIds=null;strategy;constructor(options){super();this.options={...DefaultWebSocketManagerOptions,...options};this.strategy=this.options.buildStrategy(this)}async fetchGatewayInformation(force=false){if(this.gatewayInformation){if(this.gatewayInformation.expiresAt<=Date.now()){this.gatewayInformation=null}else if(!force){return this.gatewayInformation.data}}const data=await this.options.
Event Code: ${event.code}
Clean : ${event.wasClean}
Reason : ${event.reason??"No reason received"}`);this.emit(WebSocketShardEvents.Close,event)}onReadyPacket(packet){if(!packet){this.debug(`Received broken packet: '${packet}'.`);return}this.emit(WebSocketShardEvents.Ready);this.expectedGuilds=new Set(packet.guilds.map(d=>d.id));this.status=Status2.WaitingForGuilds}gotGuild(guildId){this.expectedGuilds.delete(guildId);this.checkReady()}checkReady(){if(this.readyTimeout){clearTimeout2(this.readyTimeout);this.readyTimeout=null}if(!this.expectedGuilds.size){this.debug("Shard received all its guilds. Marking as fully ready.");this.status=Status2.Ready;this.emit(WebSocketShardEvents.AllReady);return}const hasGuildsIntent=this.manager.client.options.intents.has(GatewayIntentBits2.Guilds);const{waitGuildTimeout}=this.manager.client.options;this.readyTimeout=setTimeout3(()=>{this.debug(`Shard ${hasGuildsIntent?"did":"will"} not receive any more guild packets${hasGuildsIntent?` in ${waitGuildTimeout} ms`:""}.
Unavailable guild count: ${this.expectedGuilds.size}`);this.readyTimeout=null;this.status=Status2.Ready;this.emit(WebSocketShardEvents.AllReady,this.expectedGuilds)},hasGuildsIntent?waitGuildTimeout:0).unref()}send(data,important=false){if(important&&!deprecationEmittedForImportant){process6.emitWarning("Sending important payloads explicitly is deprecated. They are determined by their opcode implicitly now.","DeprecationWarning");deprecationEmittedForImportant=true}this.manager._ws.send(this.id,data)}};module2.exports=WebSocketShard}});var require_APPLICATION_COMMAND_PERMISSIONS_UPDATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.ApplicationCommandPermissionsUpdate.handle(packet.d)}}});var require_AUTO_MODERATION_ACTION_EXECUTION=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.AutoModerationActionExecution.handle(packet.d)}}});var require_AUTO_MODERATION_RULE_CREATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.AutoModerationRuleCreate.handle(packet.d)}}});var require_AUTO_MODERATION_RULE_DELETE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.AutoModerationRuleDelete.handle(packet.d)}}});var require_AUTO_MODERATION_RULE_UPDATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.AutoModerationRuleUpdate.handle(packet.d)}}});var require_CHANNEL_CREATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/CHANNEL_CREATE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.ChannelCreate.handle(packet.d)}}});var require_CHANNEL_DELETE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/CHANNEL_DELETE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.ChannelDelete.handle(packet.d)}}});var require_CHANNEL_PINS_UPDATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js"(exports2,module2){"use strict";var Events2=require_Events();module2.exports=(client,{d:data})=>{const channel=client.channels.cache.get(data.channel_id);const time=data.last_pin_timestamp?Date.parse(data.last_pin_timestamp):null;if(channel){channel.lastPinTimestamp=time;client.emit(Events2.ChannelPinsUpdate,channel,time)}}}});var require_CHANNEL_UPDATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/CHANNEL_UPDATE.js"(exports2,module2){"use strict";var Events2=require_Events();module2.exports=(client,packet)=>{const{old,updated}=client.actions.ChannelUpdate.handle(packet.d);if(old&&updated){client.emit(Events2.ChannelUpdate,old,updated)}}}});var require_GUILD_AUDIT_LOG_ENTRY_CREATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.GuildAuditLogEntryCreate.handle(packet.d)}}});var require_GUILD_BAN_ADD=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.GuildBanAdd.handle(packet.d)}}});var require_GUILD_BAN_REMOVE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js"(exports2,module2){"use strict";module2.exports=(client,packet)=>{client.actions.GuildBanRemove.handle(packet.d)}}});var require_GUILD_CREATE=__commonJS({"node_modules/discord.js/src/client/websocket/handlers/GUILD_CREATE.js"(exports2,module2){"use strict";var Events2=require_Events();var Status2=require_Status();module2.ex
URL: ${gatewayURL}
Recommended Shards: ${recommendedShards}`);this.debug(`Session Limit Information
Total: ${total}
Remaining: ${remaining}`);this.gateway=`${gatewayURL}/`;this.client.options.shardCount=await this._ws.getShardCount();this.client.options.shards=await this._ws.getShardIds();this.totalShards=this.client.options.shards.length;for(const id of this.client.options.shards){if(!this.shards.has(id)){const shard=new WebSocketShard(this,id);this.shards.set(id,shard);shard.on(WebSocketShardEvents.AllReady,unavailableGuilds=>{this.client.emit(Events2.ShardReady,shard.id,unavailableGuilds);this.checkShardsReady()});shard.status=Status2.Connecting}}await this._ws.connect();this.shards.forEach(shard=>{if(shard.listenerCount(WebSocketShardEvents.InvalidSession)>0&&!deprecationEmittedForInvalidSessionEvent){process6.emitWarning("The WebSocketShard#invalidSession event is deprecated and will never emit.","DeprecationWarning");deprecationEmittedForInvalidSessionEvent=true}if(shard.listenerCount(WebSocketShardEvents.Destroyed)>0&&!deprecationEmittedForDestroyedEvent){process6.emitWarning("The WebSocketShard#destroyed event is deprecated and will never emit.","DeprecationWarning");deprecationEmittedForDestroyedEvent=true}})}attachEvents(){this._ws.on(WSWebSocketShardEvents.Debug,({message:message3,shardId})=>this.debug(message3,shardId));this._ws.on(WSWebSocketShardEvents.Dispatch,({data,shardId})=>{this.client.emit(Events2.Raw,data,shardId);this.emit(data.t,data.d,shardId);const shard=this.shards.get(shardId);this.handlePacket(data,shard);if(shard.status===Status2.WaitingForGuilds&&WaitingForGuildEvents.includes(data.t)){shard.gotGuild(data.d.id)}});this._ws.on(WSWebSocketShardEvents.Ready,({data,shardId})=>{this.shards.get(shardId).onReadyPacket(data)});this._ws.on(WSWebSocketShardEvents.Closed,({code,shardId})=>{const shard=this.shards.get(shardId);shard.emit(WebSocketShardEvents.Close,{code,reason:reasonIsDeprecated,wasClean:true});if(UNRESUMABLE_CLOSE_CODES.includes(code)&&this.destroyed){shard.status=Status2.Disconnected;this.client.emit(Events2.ShardDisconnect,{code,reason:reasonIsDeprecated,wasClean:true},shardId);this.debug(GatewayCloseCodes[code],shardId);return}this.shards.get(shardId).status=Status2.Connecting;this.client.emit(Events2.ShardReconnecting,shardId)});this._ws.on(WSWebSocketShardEvents.Hello,({shardId})=>{const shard=this.shards.get(shardId);if(shard.sessionInfo){shard.closeSequence=shard.sessionInfo.sequence;shard.status=Status2.Resuming}else{shard.status=Status2.Identifying}});this._ws.on(WSWebSocketShardEvents.Resumed,({shardId})=>{const shard=this.shards.get(shardId);shard.status=Status2.Ready;shard.emit(WebSocketShardEvents.Resumed)});this._ws.on(WSWebSocketShardEvents.HeartbeatComplete,({heartbeatAt,latency,shardId})=>{this.debug(`Heartbeat acknowledged, latency of ${latency}ms.`,shardId);const shard=this.shards.get(shardId);shard.lastPingTimestamp=heartbeatAt;shard.ping=latency});this._ws.on(WSWebSocketShardEvents.Error,({error,shardId})=>{this.client.emit(Events2.ShardError,error,shardId)})}broadcast(packet){for(const shardId of this.shards.keys())this._ws.send(shardId,packet)}destroy(){if(this.destroyed)return;this.debug(`Manager was destroyed. Called by:
${new Error().stack}`);this.destroyed=true;this._ws.destroy({code:CloseCodes.Normal})}handlePacket(packet,shard){if(packet&&this.status!==Status2.Ready){if(!BeforeReadyWhitelist.includes(packet.t)){this.packetQueue.push({packet,shard});return false}}if(this.packetQueue.length){const item=this.packetQueue.shift();setImmediate2(()=>{this.handlePacket(item.packet,item.shard)}).unref()}if(packet&&PacketHandlers[packet.t]){PacketHandlers[packet.t](this.client,packet,shard)}return true}checkShardsReady(){if(this.status===Status2.Ready)return;if(this.shards.size!==this.totalShards||this.shards.some(s=>s.status!==Status2.Ready)){return}this.triggerClientReady()}triggerClientReady(){this.status=Status2.Ready;this.client.readyTimestamp=Date.now();this.client.emit(Events2.ClientReady,this.client);this.handlePacket()}};module2.exports=WebSocketManager2}});var require_BaseGuildEmojiManager=__commonJS({"node_modules/discord.js/src/managers/BaseGuildEmojiManager.js"(exports2,module2){"use strict";var CachedManager=require_CachedManager();var GuildEmoji=require_GuildEmoji();var ReactionEmoji=require_ReactionEmoji();var{parseEmoji}=require_Util();var BaseGuildEmojiManager2=class extends CachedManager{constructor(client,iterable){super(client,GuildEmoji,iterable)}resolve(emoji){if(emoji instanceof ReactionEmoji)return super.resolve(emoji.id);return super.resolve(emoji)}resolveId(emoji){if(emoji instanceof ReactionEmoji)return emoji.id;return super.resolveId(emoji)}resolveIdentifier(emoji){const emojiResolvable=this.resolve(emoji);if(emojiResolvable)return emojiResolvable.identifier;if(emoji instanceof ReactionEmoji)return emoji.identifier;if(typeof emoji==="string"){const res=parseEmoji(emoji);if(res==null?void 0:res.name.length){emoji=`${res.animated?"a:":""}${res.name}${res.id?`:${res.id}`:""}`}if(!emoji.includes("%"))return encodeURIComponent(emoji);return emoji}return null}};module2.exports=BaseGuildEmojiManager2}});var require_ChannelManager=__commonJS({"node_modules/discord.js/src/managers/ChannelManager.js"(exports2,module2){"use strict";var process6=require("node:process");var{Routes:Routes2}=require_v106();var CachedManager=require_CachedManager();var{BaseChannel}=require_BaseChannel();var{createChannel}=require_Channels();var{ThreadChannelTypes}=require_Constants();var Events2=require_Events();var cacheWarningEmitted=false;var ChannelManager2=class extends CachedManager{constructor(client,iterable){super(client,BaseChannel,iterable);const defaultCaching=this._cache.constructor.name==="Collection"||this._cache.maxSize===void 0||this._cache.maxSize===Infinity;if(!cacheWarningEmitted&&!defaultCaching){cacheWarningEmitted=true;process6.emitWarning(`Overriding the cache handling for ${this.constructor.name} is unsupported and breaks functionality.`,"UnsupportedCacheOverwriteWarning")}}_add(data,guild2,{cache:cache2=true,allowUnknownGuild=false}={}){var _a13,_b2,_c;const existing=this.cache.get(data.id);if(existing){if(cache2)existing._patch(data);(_a13=guild2==null?void 0:guild2.channels)==null?void 0:_a13._add(existing);if(ThreadChannelTypes.includes(existing.type)){(_c=(_b2=existing.parent)==null?void 0:_b2.threads)==null?void 0:_c._add(existing)}return existing}const channel=createChannel(this.client,data,guild2,{allowUnknownGuild});if(!channel){this.client.emit(Events2.Debug,`Failed to find guild, or unknown type for channel ${data.id} ${data.type}`);return null}if(cache2&&!allowUnknownGuild)this.cache.set(channel.id,channel);return channel}_remove(id){var _a13,_b2,_c,_d;const channel=this.cache.get(id);(_a13=channel==null?void 0:channel.guild)==null?void 0:_a13.channels.cache.delete(id);for(const[code,invite]of((_b2=channel==null?void 0:channel.guild)==null?void 0:_b2.invites.cache)??[]){if(invite.channelId===id)channel.guild.invites.cache.delete(code)}(_d=(_c=channel==null?void 0:channel.parent)==null?void 0:_c.threads)==null?void 0:_d.cache.delete(id);this.cache.delete(id)}async fetch(id,{allowUnknownGuild=false,cache:cache2=true,force=false}={}){if(!force){const existing=this.cache.get(id);if(existing&&!existing.partial)retu
${language2}
\`\`\``:`\`\`\`${language2}
${content}
\`\`\``}__name(codeBlock,"codeBlock");function inlineCode(content){return`\`${content}\``}__name(inlineCode,"inlineCode");function italic(content){return`_${content}_`}__name(italic,"italic");function bold(content){return`**${content}**`}__name(bold,"bold");function underscore(content){return`__${content}__`}__name(underscore,"underscore");function strikethrough(content){return`~~${content}~~`}__name(strikethrough,"strikethrough");function quote(content){return`> ${content}`}__name(quote,"quote");function blockQuote(content){return`>>> ${content}`}__name(blockQuote,"blockQuote");function hideLinkEmbed(url){return`<${url}>`}__name(hideLinkEmbed,"hideLinkEmbed");function hyperlink(content,url,title){return title?`[${content}](${url} "${title}")`:`[${content}](${url})`}__name(hyperlink,"hyperlink");function spoiler(content){return`||${content}||`}__name(spoiler,"spoiler");function userMention(userId){return`<@${userId}>`}__name(userMention,"userMention");function channelMention(channelId){return`<#${channelId}>`}__name(channelMention,"channelMention");function roleMention(roleId){return`<@&${roleId}>`}__name(roleMention,"roleMention");function chatInputApplicationCommandMention(commandName,subcommandGroupName,subcommandName,commandId){if(commandId!==void 0){return`</${commandName} ${subcommandGroupName} ${subcommandName}:${commandId}>`}if(subcommandName!==void 0){return`</${commandName} ${subcommandGroupName}:${subcommandName}>`}return`</${commandName}:${subcommandGroupName}>`}__name(chatInputApplicationCommandMention,"chatInputApplicationCommandMention");function formatEmoji(emojiId,animated=false){return`<${animated?"a":""}:_:${emojiId}>`}__name(formatEmoji,"formatEmoji");function channelLink(channelId,guildId){return`https://discord.com/channels/${guildId??"@me"}/${channelId}`}__name(channelLink,"channelLink");function messageLink(channelId,messageId,guildId){return`${guildId===void 0?channelLink(channelId):channelLink(channelId,guildId)}/${messageId}`}__name(messageLink,"messageLink");var HeadingLevel=(HeadingLevel2=>{HeadingLevel2[HeadingLevel2["One"]=1]="One";HeadingLevel2[HeadingLevel2["Two"]=2]="Two";HeadingLevel2[HeadingLevel2["Three"]=3]="Three";return HeadingLevel2})(HeadingLevel||{});function heading(content,level){switch(level){case 3:return`### ${content}`;case 2:return`## ${content}`;default:return`# ${content}`}}__name(heading,"heading");function listCallback(element,startNumber,depth=0){if(Array.isArray(element)){return element.map(element2=>listCallback(element2,startNumber,depth+1)).join("\n")}return`${" ".repeat(depth-1)}${startNumber?`${startNumber}.`:"-"} ${element}`}__name(listCallback,"listCallback");function orderedList(list,startNumber=1){return listCallback(list,Math.max(startNumber,1))}__name(orderedList,"orderedList");function unorderedList(list){return listCallback(list)}__name(unorderedList,"unorderedList");function time(timeOrSeconds,style){if(typeof timeOrSeconds!=="number"){timeOrSeconds=Math.floor(((timeOrSeconds==null?void 0:timeOrSeconds.getTime())??Date.now())/1e3)}return typeof style==="string"?`<t:${timeOrSeconds}:${style}>`:`<t:${timeOrSeconds}>`}__name(time,"time");var TimestampStyles={ShortTime:"t",LongTime:"T",ShortDate:"d",LongDate:"D",ShortDateTime:"f",LongDateTime:"F",RelativeTime:"R"};var Faces=(Faces2=>{Faces2["Shrug"]="¯_(ツ)_/¯";Faces2["Tableflip"]="(╯°□°)╯︵ ┻━┻";Faces2["Unflip"]="┬─┬ノ( º _ ºノ)";return Faces2})(Faces||{});var GuildNavigationMentions=(GuildNavigationMentions2=>{GuildNavigationMentions2["Browse"]="<id:browse>";GuildNavigationMentions2["Customize"]="<id:customize>";GuildNavigationMentions2["Guide"]="<id:guide>";return GuildNavigationMentions2})(GuildNavigationMentions||{})}});var require_src2=__commonJS({"node_modules/discord.js/src/index.js"(exports2){"use strict";var{__exportStar:__exportStar2}=(init_tslib_es6(),__toCommonJS(tslib_es6_exports));exports2.BaseClient=require_BaseClient();exports2.Client=require_Client();exports2.Shard=require_Shard();exports2.ShardClientUtil=require_ShardClientUtil();exports2.ShardingManager=req
${msg.replace(/^/gm," ")}
`)}static get default(){return Application}createAsyncCtxStorageMiddleware(){const app=this;return async function asyncCtxStorage(ctx,next){await app.ctxStorage.run(ctx,async()=>{return await next()})}}};function respond(ctx){if(false===ctx.respond)return;if(!ctx.writable)return;const res=ctx.res;let body=ctx.body;const code=ctx.status;if(statuses.empty[code]){ctx.body=null;return res.end()}if("HEAD"===ctx.method){if(!res.headersSent&&!ctx.response.has("Content-Length")){const{length}=ctx.response;if(Number.isInteger(length))ctx.length=length}return res.end()}if(null==body){if(ctx.response._explicitNullBody){ctx.response.remove("Content-Type");ctx.response.remove("Transfer-Encoding");return res.end()}if(ctx.req.httpVersionMajor>=2){body=String(code)}else{body=ctx.message||String(code)}if(!res.headersSent){ctx.type="text";ctx.length=Buffer.byteLength(body)}return res.end(body)}if(Buffer.isBuffer(body))return res.end(body);if("string"===typeof body)return res.end(body);if(body instanceof Stream)return body.pipe(res);body=JSON.stringify(body);if(!res.headersSent){ctx.length=Buffer.byteLength(body)}res.end(body)}module2.exports.HttpError=HttpError2}});var require_codes3=__commonJS({"node_modules/statuses/codes.json"(exports2,module2){module2.exports={"100":"Continue","101":"Switching Protocols","102":"Processing","103":"Early Hints","200":"OK","201":"Created","202":"Accepted","203":"Non-Authoritative Information","204":"No Content","205":"Reset Content","206":"Partial Content","207":"Multi-Status","208":"Already Reported","226":"IM Used","300":"Multiple Choices","301":"Moved Permanently","302":"Found","303":"See Other","304":"Not Modified","305":"Use Proxy","307":"Temporary Redirect","308":"Permanent Redirect","400":"Bad Request","401":"Unauthorized","402":"Payment Required","403":"Forbidden","404":"Not Found","405":"Method Not Allowed","406":"Not Acceptable","407":"Proxy Authentication Required","408":"Request Timeout","409":"Conflict","410":"Gone","411":"Length Required","412":"Precondition Failed","413":"Payload Too Large","414":"URI Too Long","415":"Unsupported Media Type","416":"Range Not Satisfiable","417":"Expectation Failed","418":"I'm a Teapot","421":"Misdirected Request","422":"Unprocessable Entity","423":"Locked","424":"Failed Dependency","425":"Too Early","426":"Upgrade Required","428":"Precondition Required","429":"Too Many Requests","431":"Request Header Fields Too Large","451":"Unavailable For Legal Reasons","500":"Internal Server Error","501":"Not Implemented","502":"Bad Gateway","503":"Service Unavailable","504":"Gateway Timeout","505":"HTTP Version Not Supported","506":"Variant Also Negotiates","507":"Insufficient Storage","508":"Loop Detected","509":"Bandwidth Limit Exceeded","510":"Not Extended","511":"Network Authentication Required"}}});var require_statuses3=__commonJS({"node_modules/statuses/index.js"(exports2,module2){"use strict";var codes=require_codes3();module2.exports=status;status.message=codes;status.code=createMessageToStatusCodeMap(codes);status.codes=createStatusCodeList(codes);status.redirect={300:true,301:true,302:true,303:true,305:true,307:true,308:true};status.empty={204:true,205:true,304:true};status.retry={502:true,503:true,504:true};function createMessageToStatusCodeMap(codes2){var map3={};Object.keys(codes2).forEach(function forEachCode(code){var message3=codes2[code];var status2=Number(code);map3[message3.toLowerCase()]=status2});return map3}function createStatusCodeList(codes2){return Object.keys(codes2).map(function mapCode(code){return Number(code)})}function getStatusCode(message3){var msg=message3.toLowerCase();if(!Object.prototype.hasOwnProperty.call(status.code,msg)){throw new Error('invalid status message: "'+message3+'"')}return status.code[msg]}function getStatusMessage(code){if(!Object.prototype.hasOwnProperty.call(status.message,code)){throw new Error("invalid status code: "+code)}return status.message[code]}function status(code){if(typeof code==="number"){return getStatusMessage(code)}if(typeof code!=="string"){throw new TypeError("code must be a number or string")}var
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message3)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message3){if(server.listenerCount("wsClientError")){const err=new Error(message3);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message3)}}}});var require_ws2=__commonJS({"node_modules/engine.io/node_modules/ws/index.js"(exports2,module2){"use strict";var WebSocket2=require_websocket4();WebSocket2.createWebSocketStream=require_stream3();WebSocket2.Server=require_websocket_server2();WebSocket2.Receiver=require_receiver3();WebSocket2.Sender=require_sender2();WebSocket2.WebSocket=WebSocket2;WebSocket2.WebSocketServer=WebSocket2.Server;module2.exports=WebSocket2}});var require_object_assign=__commonJS({"node_modules/object-assign/index.js"(exports2,module2){"use strict";var getOwnPropertySymbols=Object.getOwnPropertySymbols;var hasOwnProperty26=Object.prototype.hasOwnProperty;var propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(val===null||val===void 0){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(val)}function shouldUseNative(){try{if(!Object.assign){return false}var test1=new String("abc");test1[5]="de";if(Object.getOwnPropertyNames(test1)[0]==="5"){return false}var test2={};for(var i=0;i<10;i++){test2["_"+String.fromCharCode(i)]=i}var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n]});if(order2.join("")!=="0123456789"){return false}var test3={};"abcdefghijklmnopqrst".split("").forEach(function(letter){test3[letter]=letter});if(Object.keys(Object.assign({},test3)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(err){return false}}module2.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s<arguments.length;s++){from=Object(arguments[s]);for(var key in from){if(hasOwnProperty26.call(from,key)){to[key]=from[key]}}if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++){if(propIsEnumerable.call(from,symbols[i])){to[symbols[i]]=from[symbols[i]]}}}}return to}}});var require_lib12=__commonJS({"node_modules/cors/lib/index.js"(exports2,module2){(function(){"use strict";var assign2=require_object_assign();var vary=require_vary();var defaults3={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:false,optionsSuccessStatus:204};function isString3(s){return typeof s==="string"||s instanceof String}function isOriginAllowed(origin,allowedOrigin){if(Array.isArray(allowedOrigin)){for(var i=0;i<allowedOrigin.length;++i){if(isOriginAllowed(origin,allowedOrigin[i])){return true}}return false}else if(isString3(allowedOrigin)){return origin===allowedOrigin}else if(allowedOrigin instanceof RegExp){return allowedOrigin.test(origin)}else{return!!allowedOrigin}}function configureOrigin(options,req){var requestOrigin=req.headers.origin,headers=[],isAllowed;if(!options.origin||options.origin==="*"){headers.push([{key:"Access-Control-Allow-Origin",value:"*"}])}else if(isString3(options.origin)){headers.push([{key:"Access-Control-Allow-Origin",value:options.origin}]);headers.push([{key:"Vary",value:"Origin"}])}else{isAllowed=isOriginAllowed(requestOrigin,options.origin);headers.push([{key:"Access-Control-Allow-Origin",value:isAllowed?requestOrigin:false}]);headers.push([{key:"Vary",value:"Origin"}])}return headers}function configureMethods(options){var methods=options.methods;if(methods.join){methods=options.methods.join(",")}return{key:"Access-Control-Allow-Methods",value:methods}}function configureCredentials(options){if(options.credentials===true){return{key:"Access-Control-Allow-Credentials",value:"true"}}return null}function configureAllowedHeaders(options,req){var allowedHeaders=options.allowedHeaders||options.headers;var headers=[];if(!allowedHeaders){allowedHeaders=req.headers["access-control-request-headers"];headers.push([{key:"Vary",value:"Access-Control-R
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message3)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message3){if(server.listenerCount("wsClientError")){const err=new Error(message3);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message3)}}}});var require_ws3=__commonJS({"node_modules/socket.io-adapter/node_modules/ws/index.js"(exports2,module2){"use strict";var WebSocket2=require_websocket6();WebSocket2.createWebSocketStream=require_stream4();WebSocket2.Server=require_websocket_server3();WebSocket2.Receiver=require_receiver4();WebSocket2.Sender=require_sender3();WebSocket2.WebSocket=WebSocket2;WebSocket2.WebSocketServer=WebSocket2.Server;module2.exports=WebSocket2}});var require_in_memory_adapter=__commonJS({"node_modules/socket.io-adapter/dist/in-memory-adapter.js"(exports2){"use strict";var _a13;Object.defineProperty(exports2,"__esModule",{value:true});exports2.SessionAwareAdapter=exports2.Adapter=void 0;var events_1=require("events");var yeast_1=require_yeast();var WebSocket2=require_ws3();var canPreComputeFrame=typeof((_a13=WebSocket2===null||WebSocket2===void 0?void 0:WebSocket2.Sender)===null||_a13===void 0?void 0:_a13.frame)==="function";var Adapter2=class extends events_1.EventEmitter{constructor(nsp){super();this.nsp=nsp;this.rooms=new Map;this.sids=new Map;this.encoder=nsp.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(id,rooms){if(!this.sids.has(id)){this.sids.set(id,new Set)}for(const room of rooms){this.sids.get(id).add(room);if(!this.rooms.has(room)){this.rooms.set(room,new Set);this.emit("create-room",room)}if(!this.rooms.get(room).has(id)){this.rooms.get(room).add(id);this.emit("join-room",room,id)}}}del(id,room){if(this.sids.has(id)){this.sids.get(id).delete(room)}this._del(room,id)}_del(room,id){const _room=this.rooms.get(room);if(_room!=null){const deleted=_room.delete(id);if(deleted){this.emit("leave-room",room,id)}if(_room.size===0&&this.rooms.delete(room)){this.emit("delete-room",room)}}}delAll(id){if(!this.sids.has(id)){return}for(const room of this.sids.get(id)){this._del(room,id)}this.sids.delete(id)}broadcast(packet,opts){const flags=opts.flags||{};const packetOpts={preEncoded:true,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name;const encodedPackets=this._encode(packet,packetOpts);this.apply(opts,socket=>{if(typeof socket.notifyOutgoingListeners==="function"){socket.notifyOutgoingListeners(packet)}socket.client.writeToEngine(encodedPackets,packetOpts)})}broadcastWithAck(packet,opts,clientCountCallback,ack){const flags=opts.flags||{};const packetOpts={preEncoded:true,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name;packet.id=this.nsp._ids++;const encodedPackets=this._encode(packet,packetOpts);let clientCount=0;this.apply(opts,socket=>{clientCount++;socket.acks.set(packet.id,ack);if(typeof socket.notifyOutgoingListeners==="function"){socket.notifyOutgoingListeners(packet)}socket.client.writeToEngine(encodedPackets,packetOpts)});clientCountCallback(clientCount)}_encode(packet,packetOpts){const encodedPackets=this.encoder.encode(packet);if(canPreComputeFrame&&encodedPackets.length===1&&typeof encodedPackets[0]==="string"){const data=Buffer.from("4"+encodedPackets[0]);packetOpts.wsPreEncodedFrame=WebSocket2.Sender.frame(data,{readOnly:false,mask:false,rsv1:false,opcode:1,fin:true})}return encodedPackets}sockets(rooms){const sids=new Set;this.apply({rooms},socket=>{sids.add(socket.id)});return Promise.resolve(sids)}socketRooms(id){return this.sids.get(id)}fetchSockets(opts){const sockets=[];this.apply(opts,socket=>{sockets.push(socket)});return Promise.resolve(sockets)}addSockets(opts,rooms){this.apply(opts,socket=>{socket.join(rooms)})}delSockets(opts,rooms){this.apply(opts,socket=>{rooms.forEach(room=>socket.leave(room))})}disconnectSockets(opts,close){this.apply(opts,socket=>{socket.disconnect(close)})}apply(opts,callback){const rooms=opts.rooms;const except=this.computeEx
"&": "&amp;"
, "<": "&lt;"
, ">": "&gt;"
, '"': "&#34;"
, "'": "&#39;"
}
, _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
};
`;exports2.escapeXML=function(markup){return markup==void 0?"":String(markup).replace(_MATCH_HTML,encode_char)};function escapeXMLToString(){return Function.prototype.toString.call(this)+";\n"+escapeFuncStr}try{if(typeof Object.defineProperty==="function"){Object.defineProperty(exports2.escapeXML,"toString",{value:escapeXMLToString})}else{exports2.escapeXML.toString=escapeXMLToString}}catch(err){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}exports2.shallowCopy=function(to,from){from=from||{};if(to!==null&&to!==void 0){for(var p in from){if(!hasOwn2(from,p)){continue}if(p==="__proto__"||p==="constructor"){continue}to[p]=from[p]}}return to};exports2.shallowCopyFromList=function(to,from,list){list=list||[];from=from||{};if(to!==null&&to!==void 0){for(var i=0;i<list.length;i++){var p=list[i];if(typeof from[p]!="undefined"){if(!hasOwn2(from,p)){continue}if(p==="__proto__"||p==="constructor"){continue}to[p]=from[p]}}}return to};exports2.cache={_data:{},set:function(key,val){this._data[key]=val},get:function(key){return this._data[key]},remove:function(key){delete this._data[key]},reset:function(){this._data={}}};exports2.hyphenToCamel=function(str2){return str2.replace(/-[a-z]/g,function(match){return match[1].toUpperCase()})};exports2.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function"){return function(){return Object.create(null)}}if(!({__proto__:null}instanceof Object)){return function(){return{__proto__:null}}}return function(){return{}}}();exports2.hasOwnOnlyObject=function(obj){var o=exports2.createNullProtoObjWherePossible();for(var p in obj){if(hasOwn2(obj,p)){o[p]=obj[p]}}return o}}});var require_package6=__commonJS({"node_modules/ejs/package.json"(exports2,module2){module2.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.10",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}}});var require_ejs=__commonJS({"node_modules/ejs/lib/ejs.js"(exports2){"use strict";var fs13=require("fs");var path24=require("path");var utils=require_utils5();var scopeOptionWarned=false;var _VERSION_STRING=require_package6().version;var _DEFAULT_OPEN_DELIMITER="<";var _DEFAULT_CLOSE_DELIMITER=">";var _DEFAULT_DELIMITER="%";var _DEFAULT_LOCALS_NAME="locals";var _NAME="ejs";var _REGEX_STRING="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)";var _OPTS_PASSABLE_WITH_DATA=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"];var _OPTS_PASSABLE_WITH_DATA_EXPRESS=_OPTS_PASSABLE_WITH_DATA.concat("cache");var _BOM=/^\uFEFF/;var _JS_IDENTIFIER=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;exports2.cache=utils.cache;exports2.fileLoader=fs13.readFileSync;exports2.localsName=_DEFAULT_LOCALS_NAME;exports2.promiseImpl=new Function("return this;")().Promise;exports2.resolveInclude=function(name,filename,isDir){var dirname2=path24.dirname;var extname=path24.extname;var resolve=path24.resolve;var includePath=resolve(isDir?filename:dirname2(filename),name);var ext=extname(name);if(!ext){includePath+=".ejs"}return includePath};function resolvePaths(name,paths){var filePath;if(paths.some(function(v){filePath=exports2.resolveInclude(name,v,true);return fs13.existsSync(filePath)})){return filePath}}function getIncludePath(path25,options){var includePath;var filePath;var views=options.views;var match=/^[A-Za-z]+:\\|^\//.exec(path25);if(match&&match.length){path25=path25.replace(/^\/*/,"");if(Array.isArray(options.root)){includePath=resolvePaths(path25,options.root)}else{includePath=exports2.resolveInclu
${BUFFER_CUT_WARNING}
${trimmedBody}`}};var getLogBuffer=()=>headBuffer+bodyBuffer;var header="tx";var stackPathAliases=[];var _txAdminVersion;var _verboseFlag=false;var setConsoleEnvData=(txAdminVersion,txAdminResourcePath2,isDevMode,isVerbose)=>{_txAdminVersion=txAdminVersion;_verboseFlag=isVerbose;if(isDevMode){import_source_map_support.default.install();stackPathAliases.push([txAdminResourcePath2+"/core","@monitor"])}else{stackPathAliases.push([txAdminResourcePath2,"@monitor"])}};var stdioEolPending=false;var processStdioWriteRaw=buffer=>{if(!buffer.length)return;const comparator=typeof buffer==="string"?"\n":10;stdioEolPending=buffer[buffer.length-1]!==comparator;process.stdout.write(buffer)};var processStdioEnsureEol=()=>{if(stdioEolPending){process.stdout.write("\n");stdioEolPending=false}};var defaultStream=new import_node_stream.Writable({decodeStrings:true,defaultEncoding:"utf8",highWaterMark:64*1024,write(chunk2,encoding,callback){writeToBuffer(chunk2);process.stdout.write(chunk2);callback()}});var verboseStream=new import_node_stream.Writable({decodeStrings:true,defaultEncoding:"utf8",highWaterMark:64*1024,write(chunk2,encoding,callback){writeToBuffer(chunk2);if(_verboseFlag)process.stdout.write(chunk2);callback()}});var defaultConsole=new import_node_console.Console({stdout:defaultStream,stderr:defaultStream,colorMode:true});var verboseConsole=new import_node_console.Console({stdout:verboseStream,stderr:verboseStream,colorMode:true});var getTimestamp=()=>new Date().toLocaleString(void 0,{timeStyle:"medium",hourCycle:"h23"});var genLogPrefix=(currContext,color)=>{return color.black(`[${getTimestamp()}][${currContext}]`)};var cleanPath=x=>slash(import_node_path.default.normalize(x));var ERR_STACK_PREFIX=source_default.redBright(" => ");var DIVIDER_SIZE=60;var DIVIDER_CHAR="=";var DIVIDER=DIVIDER_CHAR.repeat(DIVIDER_SIZE);var DIR_DIVIDER=source_default.cyan(DIVIDER);var specialsColor=source_default.rgb(255,228,181).italic;var lawngreenColor=source_default.rgb(124,252,0);var orangeredColor=source_default.rgb(255,69,0);var getPrettyError=(error,multilineError)=>{const out=[];const prefixStr=`[${getTimestamp()}][tx]`;let prefixColor=source_default.redBright;let nameColor=source_default.redBright;if(error.name==="ExperimentalWarning"){prefixColor=source_default.bgYellow.black;nameColor=source_default.yellowBright}else if(multilineError){prefixColor=source_default.bgRed.black}const prefix=prefixColor(prefixStr)+" ";out.push(prefix+nameColor(`${error.name}: `)+error.message);if("type"in error)out.push(prefix+nameColor("Type:")+` ${error.type}`);if("code"in error)out.push(prefix+nameColor("Code:")+` ${error.code}`);if(typeof error.stack==="string"){const stackPrefix=multilineError?prefix:ERR_STACK_PREFIX;try{for(const line of import_error_stack_parser.default.parse(error)){if(line.fileName&&line.fileName.startsWith("node:"))continue;let outPath=cleanPath(line.fileName??"unknown");for(const[find2,replace2]of stackPathAliases){outPath=outPath.replace(find2,replace2)}const outPos=source_default.blueBright(`${line.lineNumber}:${line.columnNumber}`);const outName=source_default.yellowBright(line.functionName||"<unknown>");if(!outPath.startsWith("@monitor/core")){out.push(source_default.dim(`${stackPrefix}${outPath} > ${outPos} > ${outName}`))}else{out.push(`${stackPrefix}${outPath} > ${outPos} > ${outName}`)}}}catch(error2){out.push(`${prefix} Unnable to parse error stack.`)}}else{out.push(`${prefix} Error stack not available.`)}return out.join("\n")};var dirHandler=(data,options,consoleInstance)=>{if(!consoleInstance)consoleInstance=defaultConsole;if(data instanceof Error){consoleInstance.log(getPrettyError(data,options==null?void 0:options.multilineError));if(!(options==null?void 0:options.multilineError))consoleInstance.log()}else{consoleInstance.log(DIR_DIVIDER);if(data===void 0){consoleInstance.log(specialsColor("> undefined"))}else if(data===null){consoleInstance.log(specialsColor("> null"))}else if(data instanceof Promise){consoleInstance.log(specialsColor("> Promise"))}else if(typeof data==="boolean"){consoleInstance.log(data?lawngr
author: ${author}
# This is just a placeholder, please don't run it!
tasks:
- action: waste_time
seconds: 5
- action: waste_time
seconds: 5
`;var modulename11="Deployer";var console18=console_default(modulename11);var RECIPE_DEPLOYER_VERSION=3;var Deployer=class{constructor(originalRecipe,deploymentID,deployPath,isTrustedSource,customMetaData={}){console18.log("Deployer instance ready.");this.step="review";this.deployFailed=false;this.deployPath=deployPath;this.isTrustedSource=isTrustedSource;this.originalRecipe=originalRecipe;this.deploymentID=deploymentID;this.progress=0;this.serverName=customMetaData.serverName||txConfig.general.serverName||"";this.logLines=[];const impRecipe=originalRecipe!==false?originalRecipe:makeTemplateRecipe(customMetaData.serverName,customMetaData.author);try{this.recipe=recipeParser_default(impRecipe)}catch(error){console18.verbose.dir(error);throw new Error(`Recipe Error: ${error.message}`)}}customLog(str2){this.logLines.push(`[${getTimeHms()}] ${str2}`);console18.log(str2)}customLogError(str2){this.logLines.push(`[${getTimeHms()}] ${str2}`);console18.error(str2)}getDeployerLog(){return this.logLines.join("\n")}async confirmRecipe(userRecipe){if(this.step!=="review")throw new Error("expected review step");try{this.recipe=recipeParser_default(userRecipe)}catch(error){throw new Error(`Cannot start() deployer due to a Recipe Error: ${error.message}`)}try{await import_fs_extra3.default.ensureDir(this.deployPath)}catch(error){console18.verbose.dir(error);throw new Error(`Failed to create ${this.deployPath} with error: ${error.message}`)}this.step="input"}getRecipeVars(){if(this.step!=="input")throw new Error("expected input step");return cloneDeep_default(this.recipe.variables)}start(userInputs){if(this.step!=="input")throw new Error("expected input step");Object.assign(this.recipe.variables,userInputs);this.logLines=[];this.customLog(`Starting deployment of ${this.recipe.name}.`);this.deployFailed=false;this.progress=0;this.step="run";this.runTasks()}async markFailedDeploy(){this.deployFailed=true;try{const filePath=import_node_path7.default.join(this.deployPath,"_DEPLOY_FAILED_DO_NOT_USE");await import_fs_extra3.default.outputFile(filePath,"This deploy was failed, please do not use these files.")}catch(error){}}async runTasks(){if(this.step!=="run")throw new Error("expected run step");const contextVariables=cloneDeep_default(this.recipe.variables);contextVariables.deploymentID=this.deploymentID;contextVariables.serverName=this.serverName;contextVariables.recipeName=this.recipe.name;contextVariables.recipeAuthor=this.recipe.author;contextVariables.recipeDescription=this.recipe.description;for(let index=0;index<this.recipe.tasks.length;index++){this.progress=Math.round(index/this.recipe.tasks.length*100);const task=this.recipe.tasks[index];const taskID=`[task${index+1}:${task.action}]`;this.customLog(`Running ${taskID}...`);const taskTimeoutSeconds=task.timeoutSeconds??recipeEngine_default[task.action].timeoutSeconds;try{contextVariables.$step=`loading task ${task.action}`;await Promise.race([recipeEngine_default[task.action].run(task,this.deployPath,contextVariables),new Promise((resolve,reject2)=>{setTimeout(()=>{reject2(new Error(`timed out after ${taskTimeoutSeconds}s.`))},taskTimeoutSeconds*1e3)})]);this.logLines[this.logLines.length-1]+=" ✔️"}catch(error){this.logLines[this.logLines.length-1]+=" ❌";let msg=`Task Failed: ${error.message}
Options:
`+JSON.stringify(task,null,2);if(contextVariables.$step){msg+="\nDebug/Status: "+JSON.stringify([txEnv.txaVersion,await getOsDistro_default(),contextVariables.$step])}this.customLogError(msg);return await this.markFailedDeploy()}}this.progress=100;this.customLog("All tasks completed.");try{if(!import_fs_extra3.default.existsSync(import_node_path7.default.join(this.deployPath,"resources"))){throw new Error("this recipe didn't create a 'resources' folder.")}else if(!import_fs_extra3.default.existsSync(import_node_path7.default.join(this.deployPath,"server.cfg"))){throw new Error("this recipe didn't create a 'server.cfg' file.")}}catch(error){this.customLogError(`Deploy validation error: ${error.message}`);return await this.markFailedDeploy()}try{const task={mode:"all_vars",file:"./server.cfg"};await recipeEngine_default["replace_string"].run(task,this.deployPath,contextVariables);this.customLog("Replacing all vars in server.cfg... ✔️")}catch(error){this.customLogError(`Failed to replace all vars in server.cfg: ${error.message}`);return await this.markFailedDeploy()}this.customLog("Deploy finished and folder validated. All done!");this.step="configure";if(txEnv.isWindows){try{await(0,import_open2.default)(import_node_path7.default.normalize(this.deployPath),{app:"explorer"})}catch(error){}}}};var console19=console_default("Manager");var TxManager=class{constructor(){this.deployer=null;this.moduleShutdownHandlers=[];this.isShuttingDown=false;process.on("SIGHUP",this.gracefulShutdown.bind(this));process.on("SIGINT",this.gracefulShutdown.bind(this));process.on("SIGTERM",this.gracefulShutdown.bind(this));startReadyWatcher(()=>{txCore.fxRunner.signalStartReady()});setInterval(async()=>{txCore.webServer.webSocket.pushRefresh("status")},5e3);setTimeout(()=>{getHostData().catch(e=>{})},1e4)}async gracefulShutdown(signal){if(this.isShuttingDown){processStdioEnsureEol();console19.warn(`Got ${signal} while already shutting down.`);return}console19.warn(`Got ${signal}, shutting down...`);this.isShuttingDown=true;setTimeout(()=>{console19.error(`Graceful shutdown timed out after 5s, forcing exit...`);quitProcess(1)},5e3);await Promise.allSettled(this.moduleShutdownHandlers.map(handler=>handler()));console19.debug(`All exit handlers finished, shutting down...`);quitProcess(0)}addShutdownHandler(handler){this.moduleShutdownHandlers.push(handler)}startDeployer(recipeText,deploymentID,targetPath,isTrustedSource,customMetaData={}){if(this.deployer){throw new Error("Deployer is already running")}this.deployer=new Deployer(recipeText,deploymentID,targetPath,isTrustedSource,customMetaData)}get configState(){if((0,import_types3.isProxy)(txCore)){return"unknown"}else if(this.deployer){return"deployer"}else if(!txCore.fxRunner.isConfigured){return"setup"}else{return"ready"}}get globalStatus(){var _a13;return{configState:txManager.configState,discord:txCore.discordBot.status,runner:{isIdle:txCore.fxRunner.isIdle,isChildAlive:((_a13=txCore.fxRunner.child)==null?void 0:_a13.isAlive)??false},server:{status:txCore.fxMonitor.currentStatus,name:txConfig.general.serverName,whitelist:txConfig.whitelist.mode},scheduler:txCore.fxScheduler.getStatus()}}};var import_node_fs5=__toESM(require("node:fs"),1);var import_promises4=__toESM(require("node:fs/promises"),1);var import_node_crypto2=__toESM(require("node:crypto"),1);var import_index3=__toESM(require_lib7(),1);var Issuer=import_index3.default.Issuer;var Strategy=import_index3.default.Strategy;var TokenSet=import_index3.default.TokenSet;var errors=import_index3.default.errors;var custom2=import_index3.default.custom;var generators=import_index3.default.generators;var import_node_url2=require("node:url");var modulename12="AdminStore:CfxProvider";var console20=console_default(modulename12);var userInfoSchema=z.object({name:z.string().min(1),profile:z.string().min(1),nameid:z.string().min(1)});var getOauthState=stateKern=>{const stateSeed=`tx:cfxre:${stateKern}`;return import_node_crypto2.default.createHash("SHA1").update(stateSeed).digest("hex")};var CfxProvider=class{constructor(){const fivemIssuer=new I
If you are already registered in txAdmin, visit the Admin Manager page, and make sure the Discord ID for your user is set to \`${interaction.user.id}\`.`,true));return false}if(admin.master!==true&&!admin.permissions.includes("all_permissions")&&!admin.permissions.includes(reqPerm)){const permName=txCore.adminStore.registeredPermissions[reqPerm]??"Unknown";await interaction.reply(embedder.danger(`Your txAdmin account does not have the "${permName}" permissions required for this action.`,true));return false}return admin.name};var logDiscordAdminAction=async(adminName,message3)=>{txCore.logger.admin.write(adminName,message3)};var isValidEmbedUrl=url=>{return typeof url==="string"&&/^(https?|discord):\/\//.test(url)};var isValidButtonEmoji=emoji=>{if(typeof emoji!=="string")return false;if(/^\d{17,19}$/.test(emoji))return true;if(/^<a?:\w{2,32}:\d{17,19}>$/.test(emoji))return true;return allEmojis.has(emoji)};var invisibleChars=new Set([9,10,11,12,13,32,127,160,173,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12288,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999]);var hexInvalidString=(str2,limit=35)=>
URLs cannot be empty, if you do not want a URL then remove the URL line.`;var invalidPlaceholderMessage=`Your URL starts with \`{{\`, try removing it.
If you just tried to edit a placeholder like \`{{serverBrowserUrl}}\` or \`{{serverJoinUrl}}\`, remember that those placeholders are replaced automatically by txAdmin, meaning you do not need to edit them at all.`;var invalidEmojiMessage=`All emojis must be one of:
- UTF-8 emoji ('😄')
- Valid emoji ID ('1062339910654246964')
- Discord custom emoji (\`<:name:id>\` or \`<a:name:id>\`).
To get the full emoji code, insert it into discord, and add \`\\\` before it then send the message`;var generateStatusMessage=(rawEmbedJson=txConfig.discordBot.embedJson,rawEmbedConfigJson=txConfig.discordBot.embedConfigJson)=>{var _a13;let embedJson2;try{embedJson2=JSON.parse(rawEmbedJson);if(!(embedJson2 instanceof Object))throw new Error(`not an Object`)}catch(error){throw new Error(`Embed JSON Error: ${error.message}`)}let embedConfigJson2;try{embedConfigJson2=JSON.parse(rawEmbedConfigJson);if(!(embedConfigJson2 instanceof Object))throw new Error(`not an Object`)}catch(error){throw new Error(`Embed Config JSON Error: ${error.message}`)}const serverCfxId=txCore.cacheStore.get("fxsRuntime:cfxId");const placeholders={serverName:txConfig.general.serverName,statusString:"Unknown",statusColor:"#4C3539",serverCfxId,serverBrowserUrl:`https://servers.fivem.net/servers/detail/${serverCfxId}`,serverJoinUrl:`https://cfx.re/join/${serverCfxId}`,serverMaxClients:txCore.cacheStore.get("fxsRuntime:maxClients")??"unknown",serverClients:txCore.fxPlayerlist.onlineCount,nextScheduledRestart:"unknown",uptime:txCore.fxMonitor.currentStatus==="ONLINE"&&((_a13=txCore.fxRunner.child)==null?void 0:_a13.isAlive)?msToShortishDuration(txCore.fxRunner.child.uptime):"--"};const schedule2=txCore.fxScheduler.getStatus();if(typeof schedule2.nextRelativeMs!=="number"){placeholders.nextScheduledRestart="not scheduled"}else if(schedule2.nextSkip){placeholders.nextScheduledRestart="skipped"}else{const tempFlag=schedule2.nextIsTemp?"(tmp)":"";const relativeTime=msToShortishDuration(schedule2.nextRelativeMs);const isLessThanMinute=schedule2.nextRelativeMs<6e4;if(isLessThanMinute){placeholders.nextScheduledRestart=`right now ${tempFlag}`}else{placeholders.nextScheduledRestart=`in ${relativeTime} ${tempFlag}`}}if(txCore.fxMonitor.currentStatus==="ONLINE"){placeholders.statusString=(embedConfigJson2==null?void 0:embedConfigJson2.onlineString)??"🟢 Online";placeholders.statusColor=(embedConfigJson2==null?void 0:embedConfigJson2.onlineColor)??"#0BA70B"}else if(txCore.fxMonitor.currentStatus==="PARTIAL"){placeholders.statusString=(embedConfigJson2==null?void 0:embedConfigJson2.partialString)??"🟡 Partial";placeholders.statusColor=(embedConfigJson2==null?void 0:embedConfigJson2.partialColor)??"#FFF100"}else if(txCore.fxMonitor.currentStatus==="OFFLINE"){placeholders.statusString=(embedConfigJson2==null?void 0:embedConfigJson2.offlineString)??"🔴 Offline";placeholders.statusColor=(embedConfigJson2==null?void 0:embedConfigJson2.offlineColor)??"#A70B28"}function replacePlaceholders(inputString){Object.entries(placeholders).forEach(([key,value])=>{inputString=inputString.replaceAll(`{{${key}}}`,String(value))});return inputString}function processValue(inputValue){if(typeof inputValue==="string"){return replacePlaceholders(inputValue)}else if(Array.isArray(inputValue)){return inputValue.map(arrValue=>processValue(arrValue))}else if(inputValue!==null&&typeof inputValue==="object"){return processObject(inputValue)}else{return inputValue}}function processObject(inputData){const input=cloneDeep_default(inputData);const out={};for(const[key,value]of Object.entries(input)){const processed=processValue(value);if(key==="url"&&!isValidEmbedUrl(processed)){const messageHead=processed.length?`Invalid URL \`${processed}\`.`:`Empty URL.`;const badPlaceholderMessage=processed.startsWith("{{")?invalidPlaceholderMessage:"";throw new Error([messageHead,invalidUrlMessage,badPlaceholderMessage].join("\n"))}out[key]=processed}return out}const processedEmbedData=processObject(embedJson2);let embed;try{embed=new import_discord4.EmbedBuilder(processedEmbedData);embed.setColor(placeholders.statusColor);embed.setTimestamp();embed.setFooter({iconURL:"https://cdn.discordapp.com/emojis/1062339910654246964.webp?size=96&quality=lossless",text:`txAdmin ${txEnv.txaVersion} • Updated every minute`})}catch(error){throw new Error(`**Embed Class Error:** ${error.message}`)}let buttonsRow;try{if(Array.isArray(embedConfigJson2==null?void 0:embedConfigJson2.buttons)&&embedConfigJson2.buttons.lengt
All buttons must have:
- Label: string, not empty
- URL: string, not empty, valid URL`)}const processedUrl=processValue(cfgButton.url);if(!isValidEmbedUrl(processedUrl)){const messageHead=processedUrl.length?`Invalid URL \`${processedUrl}\``:`Empty URL`;const badPlaceholderMessage=processedUrl.startsWith("{{")?invalidPlaceholderMessage:"";throw new Error([`${messageHead} for button \`${cfgButton.label}\`.`,invalidUrlMessage,badPlaceholderMessage].join("\n"))}const btn=new import_discord4.ButtonBuilder({style:import_discord4.ButtonStyle.Link,label:processValue(cfgButton.label),url:processedUrl});if(cfgButton.emoji!==void 0){if(!isValidButtonEmoji(cfgButton.emoji)){throw new Error(`Invalid emoji for button \`${cfgButton.label}\`.
${invalidEmojiMessage}`)}btn.setEmoji(cfgButton.emoji)}buttonsRow.addComponents(btn)}}}catch(error){throw new Error(`**Embed Buttons Error:** ${error.message}`)}return{embeds:[embed],components:buttonsRow?[buttonsRow]:void 0}};var removeOldEmbed=async interaction=>{const oldChannelId=txCore.cacheStore.get("discord:status:channelId");const oldMessageId=txCore.cacheStore.get("discord:status:messageId");if(typeof oldChannelId==="string"&&typeof oldMessageId==="string"){const oldChannel=await interaction.client.channels.fetch(oldChannelId);if((oldChannel==null?void 0:oldChannel.type)===import_discord4.ChannelType.GuildText||(oldChannel==null?void 0:oldChannel.type)===import_discord4.ChannelType.GuildAnnouncement){await oldChannel.messages.delete(oldMessageId)}else{throw new Error(`oldChannel is not a guild text or announcement channel`)}}else{throw new Error(`no old message id saved, maybe was never sent, maybe it was removed`)}};var status_default=async interaction=>{var _a13,_b2;const adminName=await ensurePermission(interaction,"settings.write");if(typeof adminName!=="string")return;const isRemoveOnly=interaction.options.getSubcommand()==="remove";try{await removeOldEmbed(interaction);txCore.cacheStore.delete("discord:status:channelId");txCore.cacheStore.delete("discord:status:messageId");if(isRemoveOnly){const msg2=`Old status embed removed.`;logDiscordAdminAction(adminName,msg2);return await interaction.reply(embedder.success(msg2,true))}}catch(error){if(isRemoveOnly){return await interaction.reply(embedder.warning(`**Failed to remove old status embed:**
${error.message}`,true))}}let newStatusMessage;try{newStatusMessage=generateStatusMessage()}catch(error){return await interaction.reply(embedder.warning(`**Failed to generate new embed:**
${error.message}`,true))}try{if(((_a13=interaction.channel)==null?void 0:_a13.type)!==import_discord4.ChannelType.GuildText&&((_b2=interaction.channel)==null?void 0:_b2.type)!==import_discord4.ChannelType.GuildAnnouncement){throw new Error(`channel type not supported`)}const placeholderEmbed=new import_discord4.EmbedBuilder({description:"_placeholder message, attempting to edit with embed..._\n**Note:** If you are seeing this message, it probably means that something was wrong with the configured Embed JSONs and Discord's API rejected the request to replace this placeholder."});const newMessage=await interaction.channel.send({embeds:[placeholderEmbed]});await newMessage.edit(newStatusMessage);txCore.cacheStore.set("discord:status:channelId",interaction.channelId);txCore.cacheStore.set("discord:status:messageId",newMessage.id)}catch(error){let msg2;if(error.code===50013){msg2=`This bot does not have permission to send embed messages in this channel.
Please change the channel permissions and give this bot the \`Embed Links\` and \`Send Messages\` permissions.`}else{msg2=error.message}return await interaction.reply(embedder.warning(`**Failed to send new embed:**
${msg2}`,true))}const msg=`Status embed saved.`;logDiscordAdminAction(adminName,msg);return await interaction.reply(embedder.success(msg,true))};var import_promises6=__toESM(require("node:fs/promises"),1);var non_secure_exports={};__export(non_secure_exports,{customAlphabet:()=>customAlphabet2,nanoid:()=>nanoid2});var urlAlphabet2="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var customAlphabet2=(alphabet2,defaultSize=21)=>{return(size2=defaultSize)=>{let id="";let i=size2;while(i--){id+=alphabet2[Math.random()*alphabet2.length|0]}return id}};var nanoid2=(size2=21)=>{let id="";let i=size2;while(i--){id+=urlAlphabet2[Math.random()*64|0]}return id};var modulename18="IDGen";var console26=console_default(modulename18);var maxAttempts=10;var noIdErrorMessage="Unnable to generate new Random ID possibly due to the decreased available entropy. Please send a screenshot of the detailed information in the terminal for the txAdmin devs.";var printDiagnostics=async()=>{let uptime;let entropy;try{uptime=msToDuration(process.uptime()*1e3);entropy=(await import_promises6.default.readFile("/proc/sys/kernel/random/entropy_avail","utf8")).trim()}catch(error){entropy=error.message}const secureStorage=new Set;for(let i=0;i<100;i++){const randID=customAlphabet(consts_default.actionIdAlphabet,4)();if(!secureStorage.has(randID))secureStorage.add(randID)}const nonsecureStorage=new Set;for(let i=0;i<100;i++){const randID=customAlphabet2(consts_default.actionIdAlphabet,4)();if(!nonsecureStorage.has(randID))nonsecureStorage.add(randID)}const osDistro=await getOsDistro_default();console26.error(noIdErrorMessage);console26.error(`Uptime: ${uptime}`);console26.error(`Entropy: ${entropy}`);console26.error(`Distro: ${osDistro}`);console26.error(`txAdmin: ${txEnv.txaVersion}`);console26.error(`FXServer: ${txEnv.fxsVersionDisplay}`);console26.error(`Pterodactyl: ${convars.isPterodactyl}`);console26.error(`Unique Test: secure ${secureStorage.size}/100, non-secure ${nonsecureStorage.size}/100`)};var checkUniqueness=(storage,id,lowdbTable)=>{if(storage instanceof Set){return!storage.has(id)}else{return!storage.chain.get(lowdbTable).find({id}).value()}};var genWhitelistRequestID=storage=>{let attempts=0;while(attempts<maxAttempts){attempts++;const randFunc=attempts<=5?nanoid_exports:non_secure_exports;const id="R"+randFunc.customAlphabet(consts_default.actionIdAlphabet,4)();if(checkUniqueness(storage,id,"whitelistRequests")){return id}}printDiagnostics().catch(e=>{});throw new Error(noIdErrorMessage)};var genActionID=(storage,actionType)=>{let attempts=0;while(attempts<maxAttempts){attempts++;const randFunc=attempts<=5?nanoid_exports:non_secure_exports;const id=actionType[0].toUpperCase()+randFunc.customAlphabet(consts_default.actionIdAlphabet,3)()+"-"+randFunc.customAlphabet(consts_default.actionIdAlphabet,4)();if(checkUniqueness(storage,id,"actions")){return id}}printDiagnostics().catch(e=>{});throw new Error(noIdErrorMessage)};var DuplicateKeyError=class extends Error{constructor(message3){super(message3);this.code="DUPLICATE_KEY"}};var modulename19="DiscordBot:cmd:whitelist";var console27=console_default(modulename19);var handleMemberSubcommand=async(interaction,adminName)=>{const member=interaction.options.getMember("member");if(!member||!("user"in member)){return await interaction.reply(embedder.danger(`Failed to resolve member ID.`))}const identifier=`discord:${member.id}`;const playerName=member.nickname??member.user.username;const avatarOptions={size:64,forceStatic:true};const playerAvatar=member.displayAvatarURL(avatarOptions)??member.user.displayAvatarURL(avatarOptions);try{txCore.database.whitelist.registerApproval({identifier,playerName,playerAvatar,tsApproved:now(),approvedBy:adminName});txCore.fxRunner.sendEvent("whitelistPreApproval",{action:"added",identifier,playerName,adminName})}catch(error){return await interaction.reply(embedder.danger(`Failed to save whitelist approval: ${error.message}`))}const msg=`Added whitelist approval for ${playerName}.`;logDiscordAdminAction(adminName,msg);return await interaction.reply(emb
\`endpoint_add_tcp "${desidredEndpoint}"\`
\`endpoint_add_udp "${desidredEndpoint}"\``}else{msg=`Your config file does not specify a valid endpoint for FXServer to use.
Please delete all \`endpoint_add_*\` lines and add the following to the start of the file:
\`endpoint_add_tcp "0.0.0.0:30120"\`
\`endpoint_add_udp "0.0.0.0:30120"\``}throw new Error(msg)}const tcpudpEndpoint=Object.keys(endpoints).find(ep=>{return endpoints[ep].tcp&&endpoints[ep].udp});if(!tcpudpEndpoint){throw new Error("Your config file does not not contain a ip:port used in both `endpoint_add_tcp` and `endpoint_add_udp`. Players would not be able to connect.")}return tcpudpEndpoint.replace(/(0\.0\.0\.0|\[::\])/,"127.0.0.1")};var validateFixServerConfig=async(cfgPath2,serverDataPath)=>{const cfgAbsolutePath=resolveCFGFilePath(cfgPath2,serverDataPath);const parsedCommands=await parseRecursiveConfig(null,cfgAbsolutePath,serverDataPath);const{endpoints,errors:errors2,warnings,toCommentOut}=await validateCommands(parsedCommands);let connectEndpoint=null;try{connectEndpoint=getConnectEndpoint(endpoints)}catch(error){errors2.add(cfgAbsolutePath,false,error.message)}for(const targetCfgPath in toCommentOut.store){const actions=toCommentOut.store[targetCfgPath];try{const cfgRaw=await import_promises7.default.readFile(targetCfgPath,"utf8");const fileEOL=detectNewline(cfgRaw);const cfgLines=cfgRaw.split(/\r?\n/);for(const[ln,reason]of actions){if(ln===false)continue;if(typeof cfgLines[ln-1]!=="string"){throw new Error(`Line ${ln} not found.`)}cfgLines[ln-1]=`## [txAdmin CFG validator]: ${reason}${fileEOL}# ${cfgLines[ln-1]}`;warnings.add(targetCfgPath,ln,`Commented out: ${reason}`)}const newCfg=cfgLines.join(fileEOL);console30.warn(`Saving modified file '${targetCfgPath}'`);await import_promises7.default.writeFile(targetCfgPath,newCfg,"utf8")}catch(error){console30.verbose.error(error);for(const[ln,reason]of actions){errors2.add(targetCfgPath,ln,`Please comment out this line: ${reason}`)}}}return{connectEndpoint,errors:errors2.toMarkdown(),warnings:warnings.toMarkdown()}};var validateModifyServerConfig=async(cfgInputString,cfgPath2,serverDataPath)=>{if(typeof cfgInputString!=="string"){throw new Error("cfgInputString expected to be string.")}const cfgAbsolutePath=resolveCFGFilePath(cfgPath2,serverDataPath);const parsedCommands=await parseRecursiveConfig(cfgInputString,cfgAbsolutePath,serverDataPath);const{endpoints,errors:errors2,warnings}=await validateCommands(parsedCommands);try{const _connectEndpoint=getConnectEndpoint(endpoints)}catch(error){errors2.add(cfgAbsolutePath,false,error.message)}if(errors2.count()){return{success:false,errors:errors2.toMarkdown(),warnings:warnings.toMarkdown()}}try{console30.warn(`Saving modified file '${cfgAbsolutePath}'`);await import_promises7.default.copyFile(cfgAbsolutePath,`${cfgAbsolutePath}.bkp`);await import_promises7.default.writeFile(cfgAbsolutePath,cfgInputString,"utf8")}catch(error){throw new Error(`Failed to edit 'server.cfg' with error: ${error.message}`)}return{success:true,warnings:warnings.toMarkdown()}};var import_node_stream6=require("node:stream");var import_path=__toESM(require("path"),1);var lastBlackHoleSpewTime=0;var blackHoleSpillMaxInterval=5e3;var childProcessEventBlackHole=(...args2)=>{const currentTime=Date.now();if(currentTime-lastBlackHoleSpewTime>blackHoleSpillMaxInterval){console.verbose.error("ChildProcess unexpected event:");console.verbose.dir(args2);lastBlackHoleSpewTime=currentTime}};var getMutableConvars=(isCmdLine=false)=>{const checkPlayerJoin=txConfig.banlist.enabled||txConfig.whitelist.mode!=="disabled";const convars2=[["setr","locale",txConfig.general.language??"en"],["set","localeFile",txCore.translator.customLocalePath],["set","serverName",txConfig.general.serverName??"txAdmin"],["set","checkPlayerJoin",checkPlayerJoin],["set","menuAlignRight",txConfig.gameFeatures.menuAlignRight],["set","menuPageKey",txConfig.gameFeatures.menuPageKey],["set","playerModePtfx",txConfig.gameFeatures.playerModePtfx],["set","hideAdminInPunishments",txConfig.gameFeatures.hideAdminInPunishments],["set","hideAdminInMessages",txConfig.gameFeatures.hideAdminInMessages],["set","hideDefaultAnnouncement",txConfig.gameFeatures.hideDefaultAnnouncement],["set","hideDefaultDirectMessage",txConfig.gameFeatures.hideDefaultDirectMessage],["set","hideDefaultWarning",txConfig.gameFeatures.hideDefaultWarning],["s
${result2.errors}`;console32.error(msg);return msg}if(result2.warnings){const msg=`**Warning regarding your configuration file(s):**
${result2.warnings}`;console32.warn(msg)}netEndpointDetected=result2.connectEndpoint}catch(error){const errMsg=`server.cfg error: ${error.message}`;console32.error(errMsg);if(error.message.includes("unreadable")){console32.error("That is the file where you configure your server and start resources.");console32.error("You likely moved/deleted your server files or copied the txData folder from another server.");console32.error('To fix this issue, open the txAdmin web interface then go to "Settings > FXServer" and fix the "Server Data Folder" and "CFG File Path".')}return errMsg}txCore.fxMonitor.resetMonitorStats();txCore.webServer.webSocket.buffer("playerlist",{mutex:newServerMutex,type:"fullPlayerlist",playerlist:[]});if(shouldAnnounce){txCore.discordBot.sendAnnouncement({type:"success",description:{key:"server_actions.spawning_discord",data:{servername:fxSpawnVars.serverName}}})}const childProc=(0,import_node_child_process.spawn)(fxSpawnVars.bin,fxSpawnVars.args,{cwd:fxSpawnVars.dataPath,stdio:["pipe","pipe","pipe","pipe"]});if(!isValidChildProcess(childProc)){const errMsg=`Failed to run
${fxSpawnVars.bin}`;console32.error(errMsg);return errMsg}this.proc=new ProcessManager(childProc,{mutex:newServerMutex,netEndpoint:netEndpointDetected,onStatusUpdate:()=>{txCore.webServer.webSocket.pushRefresh("status")}});txCore.logger.fxserver.logFxserverSpawn(this.proc.pid.toString());childProc.stdout.setEncoding("utf8");childProc.stdout.on("data",txCore.logger.fxserver.writeFxsOutput.bind(txCore.logger.fxserver,ConsoleLineEnum_default.StdOut));childProc.stderr.on("data",txCore.logger.fxserver.writeFxsOutput.bind(txCore.logger.fxserver,ConsoleLineEnum_default.StdErr));const jsoninPipe=childProc.stdio[3].pipe(import_StreamValues.default.withParser());jsoninPipe.on("data",handleFd3Messages_default.bind(null,newServerMutex));childProc.stdin.on("error",childProcessEventBlackHole);childProc.stdin.on("data",childProcessEventBlackHole);childProc.stdout.on("error",childProcessEventBlackHole);childProc.stderr.on("error",childProcessEventBlackHole);childProc.stdio[3].on("error",childProcessEventBlackHole);return null}async restartServer(reason,author){const respawnDelay=this.restartSpawnDelay;if(this.isAwaitingRestartSpawnDelay){const durationStr=msToShortishDuration(respawnDelay.ms,{units:["m","s","ms"]});return`A restart is already in progress, with a delay of ${durationStr}.`}try{const killError=await this.killServer(reason,author,true);if(killError)return killError;if(respawnDelay.isBackoff){console32.warn(`Restarting the fxserver with backoff delay of ${respawnDelay.ms}ms`)}this.isAwaitingRestartSpawnDelay=true;await(0,import_promises8.setTimeout)(respawnDelay.ms);this.isAwaitingRestartSpawnDelay=false;return await this.spawnServer()}catch(error){const errMsg=`Couldn't restart the server.`;console32.error(errMsg);console32.verbose.dir(error);return errMsg}finally{this.isAwaitingRestartSpawnDelay=false}}async killServer(reason,author,isRestarting=false){if(!this.proc)return null;const shutdownDelay=Math.max(txConfig.server.shutdownNoticeDelayMs,MIN_KILL_DELAY);const reasonString=reason??"no reason provided";const messageType=isRestarting?"restarting":"stopping";const messageColor=isRestarting?"warning":"danger";const tOptions={servername:txConfig.general.serverName,reason:reasonString};if(this.isAwaitingShutdownNoticeDelay){const durationStr=msToShortishDuration(shutdownDelay,{units:["m","s","ms"]});return`A shutdown is already in progress, with a delay of ${durationStr}.`}try{if(this.proc.isAlive){this.sendEvent("serverShuttingDown",{delay:txConfig.server.shutdownNoticeDelayMs,author:typeof author==="string"?author:"txAdmin",message:txCore.translator.t(`server_actions.${messageType}`,tOptions)});this.isAwaitingShutdownNoticeDelay=true;await(0,import_promises8.setTimeout)(shutdownDelay);this.isAwaitingShutdownNoticeDelay=false}this.proc.destroy();const debugInfo=this.proc.stateInfo;this.history.push(debugInfo);this.proc=null;txCore.fxScheduler.handleServerClose();txCore.fxResources.handleServerClose();txCore.fxPlayerlist.handleServerClose(debugInfo.mutex);txCore.metrics.svRuntime.logServerClose(reasonString);txCore.discordBot.sendAnnouncement({type:messageColor,description:{key:`server_actions.${messageType}_discord`,data:tOptions}}).catch(()=>{});return null}catch(error){const msg=`Couldn't kill the server. Perhaps What Is Dead May Never Die.`;console32.error(msg);console32.verbose.dir(error);this.proc=null;return msg}finally{this.isAwaitingShutdownNoticeDelay=false}}updateMutableConvars(){console32.log("Updating FXServer ConVars.");try{const convarList=getMutableConvars(false);for(const[set3,convar,value]of convarList){this.sendCommand(set3,[convar,value],SYM_SYSTEM_AUTHOR)}return this.sendEvent("configChanged")}catch(error){console32.verbose.error("Error updating FXServer ConVars");console32.verbose.dir(error);return false}}sendEvent(eventType,data={}){if(typeof eventType!=="string"||!eventType)throw new Error("invalid eventType");try{return this.sendCommand("txaEvent",[eventType,data],SYM_SYSTEM_AUTHOR)}catch(error){console32.verbose.error(`Error writing firing server event ${eventType}`);console32.verbose.dir(error);r
`);this.writeCounter++}};var import_bytes3=__toESM(require_bytes(),1);var splitFirstLine=str2=>{const firstEolIndex=str2.indexOf("\n");if(firstEolIndex===-1){return{first:str2,rest:void 0,eol:false}}const isEolCrLf=firstEolIndex>0&&str2[firstEolIndex-1]==="\r";const foundEolLength=isEolCrLf?2:1;const firstEolAtEnd=firstEolIndex===str2.length-foundEolLength;if(firstEolAtEnd){return{first:str2,rest:void 0,eol:true}}const first=str2.substring(0,firstEolIndex+foundEolLength);const rest2=str2.substring(firstEolIndex+foundEolLength);const eol=rest2[rest2.length-1]==="\n";return{first,rest:rest2,eol}};var stripLastEol=str2=>{if(str2.endsWith("\r\n")){return{str:str2.slice(0,-2),eol:"\r\n"}}else if(str2.endsWith("\n")){return{str:str2.slice(0,-1),eol:"\n"}}return{str:str2,eol:""}};var prefixMultiline=(str2,prefix)=>{if(str2.length===0||str2==="\n")return"";let newlineIndex=str2.indexOf("\n");if(newlineIndex===-1||newlineIndex===str2.length-1){return prefix+str2}let result2=prefix;let start=0;while(newlineIndex!==-1&&newlineIndex!==str2.length-1){result2+=str2.substring(start,newlineIndex+1)+prefix;start=newlineIndex+1;newlineIndex=str2.indexOf("\n",start)}return result2+str2.substring(start)};var chalkToStr=color=>color("\0").split("\0")[0];var precalcMarkerAdminCmd=chalkToStr(source_default.bgHex("#e6b863").black);var precalcMarkerSystemCmd=chalkToStr(source_default.bgHex("#36383D").hex("#CCCCCC"));var precalcMarkerInfo=chalkToStr(source_default.bgBlueBright.black);var ANSI_RESET="\x1B[0m";var ANSI_ERASE_LINE="\x1B[K";var STYLES={[ConsoleLineEnum_default.StdOut]:null,[ConsoleLineEnum_default.StdErr]:{web:{prefix:source_default.bgRedBright.bold.black,line:source_default.bold.redBright},stdout:{prefix:source_default.bgRedBright.bold.black,line:source_default.bold.redBright}},[ConsoleLineEnum_default.MarkerAdminCmd]:{web:{prefix:source_default.bold,line:x=>`${precalcMarkerAdminCmd}${x}${ANSI_ERASE_LINE}${ANSI_RESET}`},stdout:false},[ConsoleLineEnum_default.MarkerSystemCmd]:{web:{prefix:source_default.bold,line:x=>`${precalcMarkerSystemCmd}${x}${ANSI_ERASE_LINE}${ANSI_RESET}`},stdout:false},[ConsoleLineEnum_default.MarkerInfo]:{web:{prefix:source_default.bold,line:x=>`${precalcMarkerInfo}${x}${ANSI_ERASE_LINE}${ANSI_RESET}`},stdout:{prefix:source_default.bgBlueBright.black,line:source_default.bgBlueBright.black}}};var FORCED_EOL="↩\n";var prefixChar="║";var getConsoleLinePrefix=prefix=>prefixChar+prefix.padStart(20," ")+prefixChar;var colorLines=(str2,color)=>{if(!color)return str2;const stripped=stripLastEol(str2);return color(stripped.str)+stripped.eol};var ConsoleTransformer=class{constructor(){this.lastEol=true;this.lastSrc="0:undefined";this.lastMarkerTs=0;this.STYLES=STYLES;this.PREFIX_SYSTEM=getConsoleLinePrefix("TXADMIN");this.PREFIX_STDERR=getConsoleLinePrefix("STDERR")}process(type2,data,context){if(!data.length)return{webBuffer:"",stdoutBuffer:"",fileBuffer:""};const src=`${type2}:${context}`;if(data==="\n"||data==="\r\n"){this.lastEol=true;this.lastSrc=src;return{webBuffer:"\n",stdoutBuffer:"\n",fileBuffer:"\n"}}let webBuffer="";let stdoutBuffer="";let fileBuffer="";if(!this.lastEol){if(src!==this.lastSrc){webBuffer+=FORCED_EOL;stdoutBuffer+=FORCED_EOL;fileBuffer+=FORCED_EOL;const prefixed2=this.prefixChunk(type2,data,context);webBuffer+=this.getTimeMarker()+prefixed2.webBuffer;stdoutBuffer+=prefixed2.stdoutBuffer;fileBuffer+=prefixed2.fileBuffer;this.lastEol=data[data.length-1]==="\n";this.lastSrc=src;return{webBuffer,stdoutBuffer,fileBuffer}}const parts=splitFirstLine(data);fileBuffer+=parts.first;const style=this.STYLES[type2];if(style===null){webBuffer+=parts.first;stdoutBuffer+=parts.first}else{webBuffer+=colorLines(parts.first,style.web.line);stdoutBuffer+=style.stdout?colorLines(parts.first,style.stdout.line):""}if(parts.rest){const prefixed2=this.prefixChunk(type2,parts.rest,context);webBuffer+=this.getTimeMarker()+prefixed2.webBuffer;stdoutBuffer+=prefixed2.stdoutBuffer;fileBuffer+=prefixed2.fileBuffer}this.lastEol=parts.eol;return{webBuffer,stdoutBuffer,fileBuffer}}const prefixed=this.prefixChunk(type2,da
`)}catch(error){console36.verbose.error("Error processing FD3 txAdminLogData:");console36.verbose.dir(error)}}}processEvent(eventData,mutex){var _a13,_b2,_c;let srcObject;let srcString;if(eventData.src==="tx"){srcObject={id:false,name:"txAdmin"};srcString="txAdmin"}else if(typeof eventData.src==="number"&&eventData.src>0){const player=txCore.fxPlayerlist.getPlayerById(eventData.src);if(player){const playerID=`${mutex}#${eventData.src}`;srcObject={id:playerID,name:player.displayName};srcString=`[${playerID}] ${player.displayName}`}else{srcObject={id:false,name:"UNKNOWN PLAYER"};srcString="UNKNOWN PLAYER";console36.verbose.warn("Unknown numeric event source from object:");console36.verbose.dir(eventData)}}else{srcObject={id:false,name:"UNKNOWN"};srcString="UNKNOWN"}let eventMessage;if(eventData.type==="playerJoining"){const idsString=summarizeIdsArray((_a13=eventData==null?void 0:eventData.data)==null?void 0:_a13.ids);eventMessage=`joined with identifiers ${idsString}`}else if(eventData.type==="playerDropped"){const reason=eventData.data.reason||"UNKNOWN REASON";eventMessage=`disconnected (${reason})`}else if(eventData.type==="playerJoinDenied"){const reason=eventData.data.reason??"UNKNOWN REASON";eventMessage=`player join denied due to ${reason}`}else if(eventData.type==="ChatMessage"){const text=typeof eventData.data.text==="string"?eventData.data.text.replace(/\^([0-9])/g,""):"unknown message";eventMessage=typeof eventData.data.author==="string"&&eventData.data.author!==srcObject.name?`(${eventData.data.author}): said "${text}"`:`said "${text}"`}else if(eventData.type==="DeathNotice"){const cause=eventData.data.cause||"unknown";if(typeof eventData.data.killer==="number"&&eventData.data.killer>0){const killer=txCore.fxPlayerlist.getPlayerById(eventData.data.killer);if(killer){eventMessage=`died from ${cause} by ${killer.displayName}`}else{eventMessage=`died from ${cause} by unknown killer`}}else{eventMessage=`died from ${cause}`}}else if(eventData.type==="explosionEvent"){const expType=eventData.data.explosionType||"UNKNOWN";eventMessage=`caused an explosion (${expType})`}else if(eventData.type==="CommandExecuted"){const command=eventData.data||"unknown";eventMessage=`executed: /${command}`}else if(eventData.type==="LoggerStarted"){eventMessage="Logger started";txCore.metrics.playerDrop.handleServerBootData(eventData.data);if(typeof((_b2=eventData.data)==null?void 0:_b2.projectName)==="string"&&eventData.data.projectName.length){txCore.cacheStore.set("fxsRuntime:projectName",eventData.data.projectName)}}else if(eventData.type==="DebugMessage"){eventMessage=typeof eventData.data==="string"?`Debug Message: ${eventData.data}`:"Debug Message: unknown"}else if(eventData.type==="MenuEvent"){txCore.metrics.txRuntime.menuCommands.count(((_c=eventData.data)==null?void 0:_c.action)??"unknown");eventMessage=typeof eventData.data.message==="string"?`${eventData.data.message}`:"did unknown action"}else{console36.verbose.warn(`Unrecognized event: ${eventData.type}`);console36.verbose.dir(eventData);eventMessage=eventData.type}const localeTime=new Date(eventData.ts).toLocaleTimeString();eventMessage=eventMessage.replace(/\n/g," ");return{eventObject:{ts:eventData.ts,type:eventData.type,src:srcObject,msg:eventMessage},eventString:`[${localeTime}] ${srcString}: ${eventMessage}`}}readPartialNewer(timestamp2,sliceLength){const limitIndex=this.recentBuffer.findIndex(x=>x.ts>timestamp2);return this.recentBuffer.slice(limitIndex,limitIndex+sliceLength)}readPartialOlder(timestamp2,sliceLength){const limitIndex=this.recentBuffer.findIndex(x=>x.ts>=timestamp2);if(limitIndex===-1){return this.recentBuffer.slice(-sliceLength)}else{return this.recentBuffer.slice(Math.max(0,limitIndex-sliceLength),limitIndex)}}readFiltered(){throw new Error("Not yet implemented.")}};var modulename26="Logger";var console37=console_default(modulename26);var Logger=class{constructor(){this.basePath=`${txEnv.profilePath}/logs/`;this.admin=new AdminLogger(this.basePath,txConfig.logger.admin);this.fxserver=new FXServerLogger(this.basePath,txConfig.logger.fxserver);this.s
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2NCbB5DvpR7F8qHF9SyA
xJKv9lpGO2PiU5wYUmEQaa0IUrUZmQ8ivsoOyCZOGKN9PESsVyqZPx37fhtAIqNo
AXded6K6ortngEghqQloK3bi3hk8mclGXKmUhwimfrw77EIzd8dycSFQTwV+hiy6
osF2150yfeGRnD1vGbc6iS7Ewer0Zh9rwghXnl/jTupVprQggrhVIg62ZxmrQ0Gd
lj9pVXSu6QV/rjNbAVIiLFBGTjsHIKORQWV32oCguXu5krNvI+2lCBpOowY2dTO/
+TX0xXHgkGAQIdL0SdpD1SIe57hZsA2mOVitNwztE+KAhYsVBSqasGbly0lu7NDJ
oQIDAQAB
-----END PUBLIC KEY-----`;var jweHeader={alg:"RSA-OAEP-256",enc:"A256GCM",kid:"2023-05-21_stats"};var TxRuntimeMetrics=class{constructor(){this.#fxServerBootSeconds=false;this.loginOrigins=new MultipleCounter;this.loginMethods=new MultipleCounter;this.botCommands=new MultipleCounter;this.menuCommands=new MultipleCounter;this.banCheckTime=new QuantileArray(5e3,50);this.whitelistCheckTime=new QuantileArray(5e3,50);this.playersTableSearchTime=new QuantileArray(5e3,50);this.historyTableSearchTime=new QuantileArray(5e3,50);this.currHbData='{"error": "not yet initialized in TxRuntimeMetrics"}';this.monitorStats={healthIssues:{fd3:0,http:0},restartReasons:{close:0,heartBeat:0,healthCheck:0,both:0}};setImmediate(()=>{this.loadStatsPublicKey()});setTimeout(()=>{this.refreshHbData().catch(e=>{})},15e3);setInterval(()=>{this.refreshHbData().catch(e=>{})},6e4)}#publicKey;#fxServerBootSeconds;async loadStatsPublicKey(){try{this.#publicKey=await importSPKI(statsPublicKeyPem,"RS256")}catch(error){fatalError_default.StatsTxRuntime(0,"Failed to load stats public key.",error)}}registerFxserverBoot(seconds){if(!Number.isInteger(seconds)||seconds<0){this.#fxServerBootSeconds=false}this.#fxServerBootSeconds=seconds;console41.verbose.debug(`FXServer booted in ${seconds} seconds.`)}registerFxserverRestart(reason){if(!(reason in this.monitorStats.restartReasons))return;this.monitorStats.restartReasons[reason]++}registerFxserverHealthIssue(type2){if(!(type2 in this.monitorStats.healthIssues))return;this.monitorStats.healthIssues[type2]++}async refreshHbData(){if(!this.#publicKey){console41.verbose.warn("Cannot refreshHbData because this.#publicKey is not set.");return}try{const hostData=getHostStaticData();const statsData={isZapHosting:convars.isZapHosting,isPterodactyl:convars.isPterodactyl,osDistro:hostData.osDistro,hostCpuModel:`${hostData.cpu.manufacturer} ${hostData.cpu.brand}`,fxServerBootSeconds:this.#fxServerBootSeconds,loginOrigins:this.loginOrigins,loginMethods:this.loginMethods,botCommands:txConfig.discordBot.enabled?this.botCommands:false,menuCommands:txConfig.gameFeatures.menuEnabled?this.menuCommands:false,banCheckTime:txConfig.banlist.enabled?this.banCheckTime:false,whitelistCheckTime:txConfig.whitelist.mode!=="disabled"?this.whitelistCheckTime:false,playersTableSearchTime:this.playersTableSearchTime,historyTableSearchTime:this.historyTableSearchTime,adminCount:Array.isArray(txCore.adminStore.admins)?txCore.adminStore.admins.length:1,banCheckingEnabled:txConfig.banlist.enabled,whitelistMode:txConfig.whitelist.mode,recipeName:txCore.cacheStore.get("deployer:recipe")??"not_in_cache",tmpConfigFlags:[txConfig.gameFeatures.hideDefaultAnnouncement&&"global.hideDefaultAnnouncement",txConfig.gameFeatures.hideDefaultDirectMessage&&"global.hideDefaultDirectMessage",txConfig.gameFeatures.hideDefaultScheduledRestartWarning&&"global.hideDefaultScheduledRestartWarning",txConfig.gameFeatures.hideDefaultWarning&&"global.hideDefaultWarning",txConfig.gameFeatures.hideAdminInPunishments&&"global.hideAdminInPunishments",txConfig.gameFeatures.hideAdminInMessages&&"global.hideAdminInMessages"].filter(x=>x),playerDb:txCore.database.stats.getDatabaseStats(),perfSummary:txCore.metrics.svRuntime.getServerPerfSummary()};const encodedHbData=new TextEncoder().encode(JSON.stringify(statsData));const jwe=await new CompactEncrypt(encodedHbData).setProtectedHeader(jweHeader).encrypt(this.#publicKey);this.currHbData=JSON.stringify({"$statsVersion":JWE_VERSION,jwe})}catch(error){console41.verbose.error("Error while updating stats data.");console41.verbose.dir(error);this.currHbData=JSON.stringify({error:error.message})}}};var import_promises13=__toESM(require("node:fs/promises"),1);var zIntNonNegative2=numberType().int().nonnegative();var PDLServerBootDataSchema=objectType({gameName:stringType().min(1).default("unknown"),gameBuild:stringType().min(1).default("unknown"),fxsVersion:stringType().min(1).default("unknown"),resources:arrayType(stringType().min(1)),projectName:stringType().optional()});var PDLFxsChangedEventSchema=objectType({ts:zIntNonNegative2,type:lit
This likely means you are attempting to use a path from your computer on a remote server.
If you want to use your local files, you will first need to upload them to the server.`}else if((_a13=error.message)==null?void 0:_a13.includes("ENOENT")){return`The path provided does not exist:
\`${targetPath}\``}else if(((_b2=error.message)==null?void 0:_b2.includes("EACCES"))||((_c=error.message)==null?void 0:_c.includes("EPERM"))){return`The path provided is not accessible:
\`${targetPath}\``}return error.message};var fsp12=__toESM(require("node:fs/promises"),1);var path13=__toESM(require("node:path"),1);var IGNORED_DIRS=["cache","db","node_modules",".git",".idea",".vscode"];var MANIFEST_FILES=["fxmanifest.lua","__resource.lua"];var RES_CATEGORIES_LIMIT=250;var CFG_SIZE_LIMIT=32*1024;var getServerDataContent=async serverDataPath=>{let resourcesInRoot=false;const content=[];let resourceCategories=0;const rootEntries=await fsp12.readdir(serverDataPath,{withFileTypes:true});for(const entry of rootEntries){if(entry.isDirectory()){content.push([entry.name,false]);if(entry.name==="resources"){resourcesInRoot=true}}else if(entry.isFile()){const stat3=await fsp12.stat(path13.join(serverDataPath,entry.name));content.push([entry.name,stat3.size])}}if(!resourcesInRoot)return content;const categoriesToScan=[path13.join(serverDataPath,"resources")];while(categoriesToScan.length){if(resourceCategories>=RES_CATEGORIES_LIMIT){throw new Error(`Scanning above the limit of ${RES_CATEGORIES_LIMIT} resource categories.`)}resourceCategories++;const currCategory=categoriesToScan.shift();const currCatDirEntries=await fsp12.readdir(currCategory,{withFileTypes:true});for(const catDirEntry of currCatDirEntries){const catDirEntryFullPath=path13.join(currCategory,catDirEntry.name);const catDirEntryRelativePath=path13.relative(serverDataPath,catDirEntryFullPath);if(catDirEntry.isDirectory()){content.push([path13.relative(serverDataPath,catDirEntryFullPath),false]);if(!catDirEntry.name.length||IGNORED_DIRS.includes(catDirEntry.name))continue;if(catDirEntry.name[0]==="["&&catDirEntry.name[catDirEntry.name.length-1]==="]"){categoriesToScan.push(catDirEntryFullPath)}else{const resourceFullPath=catDirEntryFullPath;const resourceRelativePath=catDirEntryRelativePath;let resourceHasManifest=false;const resDirEntries=await fsp12.readdir(resourceFullPath,{withFileTypes:true});for(const resDirEntry of resDirEntries){const resEntryFullPath=path13.join(resourceFullPath,resDirEntry.name);const resEntryRelativePath=path13.join(resourceRelativePath,resDirEntry.name);if(resDirEntry.isDirectory()){content.push([resEntryRelativePath,false])}else if(resDirEntry.isFile()){const stat3=await fsp12.stat(resEntryFullPath);content.push([resEntryRelativePath,stat3.size]);if(!resourceHasManifest&&MANIFEST_FILES.includes(resDirEntry.name)){resourceHasManifest=true}}};}}else if(catDirEntry.isFile()){const stat3=await fsp12.stat(catDirEntryFullPath);content.push([catDirEntryRelativePath,stat3.size])}}}content.sort(([aName,aSize],[bName,bSize])=>{const aDir=path13.parse(aName).dir;const bDir=path13.parse(bName).dir;if(aDir!==bDir){return aName.localeCompare(bName)}else if(aSize===false&&bSize!==false){return-1}else if(aSize!==false&&bSize===false){return 1}else{return aName.localeCompare(bName)}});return content};var getServerDataConfigs=async(serverDataPath,serverDataContent)=>{const configs=[];for(const[entryPath,entrySize]of serverDataContent){if(typeof entrySize!=="number"||!entryPath.endsWith(".cfg"))continue;if(entrySize>CFG_SIZE_LIMIT){configs.push([entryPath,"file is too big"])}try{const rawData=await fsp12.readFile(path13.join(serverDataPath,entryPath),"utf8");configs.push([entryPath,rawData])}catch(error){configs.push([entryPath,error.message])}}return configs};var isValidServerDataPath=async dataPath3=>{var _a13,_b2,_c;try{const rootEntries=await getPathSubdirs(dataPath3);if(!rootEntries.some(e=>e.name==="resources")){throw new Error("The provided directory does not contain a `resources` subdirectory.")}}catch(err){const error=err;let msg=getFsErrorMdMessage(error,dataPath3);if(dataPath3.includes("resources")){msg=`Looks like this path is the \`resources\` folder, but the server data path must be the folder that contains the resources folder instead of the resources folder itself.
**Try removing the \`resources\` part at the end of the path.**`}throw new Error(msg)}try{const resourceEntries=await getPathSubdirs(path13.join(dataPath3,"resources"));if(!resourceEntries.length){throw new Error("The `resources` directory is empty.")}}catch(err){const error=err;let msg=error.message;if((_a13=error.message)==null?void 0:_a13.includes("ENOENT")){msg=`The \`resources\` directory does not exist inside the provided Server Data Folder:
\`${dataPath3}\``}else if(((_b2=error.message)==null?void 0:_b2.includes("EACCES"))||((_c=error.message)==null?void 0:_c.includes("EPERM"))){msg=`The \`resources\` directory is not accessible inside the provided Server Data Folder:
\`${dataPath3}\``}throw new Error(msg)}return true};var findPotentialServerDataPaths=async initialPath=>{const checkTarget=async target=>{try{return await isValidServerDataPath(target)}catch(error){return false}};const parentPath=path13.join(initialPath,"..");const isParentPath=await checkTarget(parentPath);if(isParentPath)return parentPath;try{const siblingPaths=await getPathSubdirs(parentPath);for(const sibling of siblingPaths){const siblingPath=path13.join(parentPath,sibling.name);if(siblingPath===initialPath)continue;if(await checkTarget(siblingPath))return siblingPath}}catch(error){}try{const childPaths=await getPathSubdirs(initialPath);for(const child of childPaths){const childPath=path13.join(initialPath,child.name);if(await checkTarget(childPath))return childPath}}catch(error){}const resourceSplitAttempt=initialPath.split(/[/\\]resources(?:[/\\]?|$)/,2);if(resourceSplitAttempt.length===2){const potentialServerDataPath=resourceSplitAttempt[0];if(await checkTarget(potentialServerDataPath))return potentialServerDataPath}return false};var import_promises15=__toESM(require("node:fs/promises"),1);var import_node_path12=__toESM(require("node:path"),1);var import_node_crypto4=require("node:crypto");var hashFile=async filePath=>{const rawFile=await import_promises15.default.readFile(filePath,"utf8");const normalized=rawFile.normalize("NFKC").replace(/\r\n/g,"\n").replace(/^\uFEFF/,"");return(0,import_node_crypto4.createHash)("sha1").update(normalized).digest("hex")};var MAX_FILES=300;var MAX_TOTAL_SIZE=52428800;var MAX_FILE_SIZE=20971520;var MAX_DEPTH=10;var MAX_EXECUTION_TIME=30*1e3;var IGNORED_FOLDERS=["db","cache","dist",".reports","license_report","tmp_core_tsc","node_modules","txData"];async function scanMonitorFiles(){const rootPath=txEnv.txAdminResourcePath;const allFiles=[];let totalFiles=0;let totalSize=0;try{const tsStart=Date.now();const scanDir=async(dir,depth=0)=>{if(depth>MAX_DEPTH){throw new Error("MAX_DEPTH")}let filesFound=0;const entries2=await import_promises15.default.readdir(dir,{withFileTypes:true});for(const entry of entries2){if(totalFiles>=MAX_FILES){throw new Error("MAX_FILES")}else if(totalSize>=MAX_TOTAL_SIZE){throw new Error("MAX_TOTAL_SIZE")}else if(Date.now()-tsStart>MAX_EXECUTION_TIME){throw new Error("MAX_EXECUTION_TIME")}const entryPath=import_node_path12.default.join(dir,entry.name);let relativeEntryPath=import_node_path12.default.relative(rootPath,entryPath);relativeEntryPath="./"+relativeEntryPath.split(import_node_path12.default.sep).join(import_node_path12.default.posix.sep);if(entry.isDirectory()){if(IGNORED_FOLDERS.includes(entry.name)){continue}await scanDir(entryPath,depth+1)}else if(entry.isFile()){const stats=await import_promises15.default.stat(entryPath);if(stats.size>MAX_FILE_SIZE){throw new Error("MAX_SIZE")}allFiles.push({path:relativeEntryPath,size:stats.size,hash:await hashFile(entryPath)});filesFound++;totalFiles++;totalSize+=stats.size}}return filesFound};await scanDir(rootPath);allFiles.sort((a,b)=>a.path.localeCompare(b.path));return{totalFiles,totalSize,allFiles}}catch(error){return{error:error.message,totalFiles,totalSize,allFiles}}}var modulename37="WebServer:SendDiagnosticsReport";var console48=console_default(modulename37);var reportIdCache=new MemCache(60);var maskedKeywords=["key","license","pass","private","secret","token","webhook"];var maskString=input=>input.replace(/\w/gi,"x");var maskIps=input=>input.replace(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/gi,"x.x.x.x");async function SendDiagnosticsReport(ctx){var _a13,_b2,_c,_d;const sendTypedResp2=data=>ctx.send(data);const cachedReportId=reportIdCache.get();if(cachedReportId){return sendTypedResp2({error:`You can send at most one report per minute. Your last report ID was ${cachedReportId}.`})}let diagnostics;try{const[host,txadmin,fxserver,proccesses]=await Promise.all([getHostData(),getTxAdminData(),getFXServerData(),getProcessesData()]);diagnostics={host,txadmin,fxserver,proccesses}}catch(error){}const adminList=txCore.adminStore.getRawAdminsList().map(a=>({...a,password_hash:"[REDACTED]"}));const storedConfi
- Make sure the server is online (try to join it). <br>
- Make sure you don't have more than 1000 resources. <br>
- Make sure you are not running the FXServer outside of txAdmin. <br>
- Check the <strong>Live Console</strong> for any errors which may indicate that some resource has a malformed <code>fxmanifest.lua</code> file.`;const cmdSuccess=txCore.fxRunner.sendCommand("txaReportResources",[],SYM_SYSTEM_AUTHOR);if(!cmdSuccess){return ctx.utils.render("main/message",{message:timeoutMessage})}let tListTimer;let tErrorTimer;const tList=new Promise((resolve,reject2)=>{tListTimer=setInterval(()=>{if(txCore.fxResources.resourceReport&&new Date-txCore.fxResources.resourceReport.ts<=1e3&&Array.isArray(txCore.fxResources.resourceReport.resources)){clearTimeout(tListTimer);clearTimeout(tErrorTimer);const resGroups=processResources(txCore.fxResources.resourceReport.resources);const renderData2={headerTitle:"Resources",resGroupsJS:JSON.stringify(resGroups),resGroups,disableActions:ctx.admin.hasPermission("commands.resources")?"":"disabled"};resolve(["main/resources",renderData2])}},100)});const tError=new Promise((resolve,reject2)=>{tErrorTimer=setTimeout(()=>{clearTimeout(tListTimer);resolve(["main/message",{message:timeoutMessage}])},1e3)});const[view,renderData]=await Promise.race([tList,tError]);return ctx.utils.render(view,renderData)}function processResources(resList){const resGroupList={};resList.forEach(resource=>{if(isUndefined2(resource.name)||isUndefined2(resource.status)||isUndefined2(resource.path)||resource.path===""){return}const subPath=getResourceSubPath(resource.path);const resData={name:resource.name,divName:(0,import_slug.default)(resource.name),status:resource.status,statusClass:resource.status==="started"?"success":"danger",version:resource.version?`(${resource.version.trim()})`:"",author:resource.author?`${resource.author.trim()}`:"",description:resource.description?resource.description.trim():""};if(resGroupList.hasOwnProperty(subPath)){resGroupList[subPath].push(resData)}else{resGroupList[subPath]=[resData]}});const finalList=[];Object.keys(resGroupList).forEach(subPath=>{const subPathData={subPath,divName:(0,import_slug.default)(subPath),resources:resGroupList[subPath].sort(dynamicSort("name"))};finalList.push(subPathData)});return finalList}var modulename40="WebServer:PerfChart";var console51=console_default(modulename40);var paramsSchema=z.object({thread:z.string()});var requiredMinDataAge=30*60*1e3;var chartWindow30h=30*60*60*1e3;async function perfChart(ctx){const sendTypedResp2=data=>ctx.send(data);const schemaRes=paramsSchema.safeParse(ctx.request.params);if(!schemaRes.success){return sendTypedResp2({fail_reason:"bad_request"})}const chartData=txCore.metrics.svRuntime.getChartData(schemaRes.data.thread);if("fail_reason"in chartData){return sendTypedResp2(chartData)}const{threadPerfLog,boundaries}=chartData;const windowCutoffTs=Date.now()-chartWindow30h;const filteredThreadPerfLog=threadPerfLog.filter(log2=>log2.ts>=windowCutoffTs);const oldestDataLogged=filteredThreadPerfLog.find(log2=>log2.type==="data");if(!oldestDataLogged){return sendTypedResp2({fail_reason:"not_enough_data"})}else if(oldestDataLogged.ts>Date.now()-requiredMinDataAge){return sendTypedResp2({fail_reason:"not_enough_data"})}return sendTypedResp2({boundaries,threadPerfLog:filteredThreadPerfLog})}var modulename41="WebServer:PlayerDrops";var console52=console_default(modulename41);var querySchema=z.object({detailedWindow:z.string().optional(),detailedDaysAgo:z.string().optional()});var SUMMARY_DEFAULT_HOURS=14*24;var DETAILED_DEFAULT_HOURS=7*24;async function playerDrops(ctx){const sendTypedResp2=data=>ctx.send(data);const schemaRes=querySchema.safeParse(ctx.request.query);if(!schemaRes.success){return sendTypedResp2({fail_reason:`Invalid request query: ${schemaRes.error.message}`})}const{detailedWindow,detailedDaysAgo}=schemaRes.data;const lookupTs=Date.now();const summary=txCore.metrics.playerDrop.getRecentSummary(SUMMARY_DEFAULT_HOURS);let detailedWindowStart,detailedWindowEnd;if(detailedWindow){try{const[windowStartStr,windowEndStr]=detailedWindow.split(",");detailedWindowStart=new Date(windowStartStr).getTime();detailedWindowEnd=Math.min(lookupTs,new Date(windowEndStr).getTime())}catch(error){return sen
${userInfo.nameid.toString()}`})}ctx.sessTools.set({tmpAddMasterUserInfo:userInfo});return ctx.send({fivemName:userInfo.name,fivemId:fivemIdentifier,profilePicture:userInfo.picture})}var modulename45="WebServer:AuthAddMasterSave";var console56=console_default(modulename45);var bodySchema3=z.object({password:z.string().min(consts_default.adminPasswordMinLength).max(consts_default.adminPasswordMaxLength),discordId:z.string().optional()});async function AuthAddMasterSave(ctx){const schemaRes=bodySchema3.safeParse(ctx.request.body);if(!schemaRes.success){return ctx.send({error:`Invalid request body: ${schemaRes.error.message}`})}const{password,discordId}=schemaRes.data;if(txCore.adminStore.hasAdmins()){return ctx.send({error:`master_already_set`})}if(typeof discordId==="string"&&!consts_default.validIdentifierParts.discord.test(discordId)){return ctx.send({error:`Invalid Discord ID.`})}const inboundSession=ctx.sessTools.get();if(!inboundSession||!(inboundSession==null?void 0:inboundSession.tmpAddMasterUserInfo)){return ctx.send({error:`Invalid browser session.`})}const userInfo=inboundSession.tmpAddMasterUserInfo;const fivemIdentifier=getIdFromOauthNameid(userInfo.nameid);if(!fivemIdentifier){return ctx.send({error:`Could not extract the user identifier from userInfo.nameid.
Please report this to the txAdmin dev team.
${userInfo.nameid.toString()}`})}try{const vaultAdmin=txCore.adminStore.createAdminsFile(userInfo.name,fivemIdentifier,discordId,password,true);if(userInfo.picture){txCore.cacheStore.set(`admin:picture:${userInfo.name}`,userInfo.picture)}const sessData={type:"cfxre",username:userInfo.name,csrfToken:txCore.adminStore.genCsrfToken(),expiresAt:Date.now()+864e5,identifier:fivemIdentifier};ctx.sessTools.set({auth:sessData});const authedAdmin=new AuthedAdmin(vaultAdmin,sessData.csrfToken);authedAdmin.logAction(`created admins file`);return ctx.send(authedAdmin.getAuthData())}catch(error){ctx.sessTools.destroy();console56.error(`Failed to create session: ${error.message}`);return ctx.send({error:`Failed to create session: ${error.message}`})}}var modulename46="WebServer:AuthProviderRedirect";var console57=console_default(modulename46);var querySchema2=z.object({origin:z.string()});async function AuthProviderRedirect(ctx){const schemaRes=querySchema2.safeParse(ctx.request.query);if(!schemaRes.success){return ctx.send({error:`Invalid request query: ${schemaRes.error.message}`})}const{origin}=schemaRes.data;if(!txCore.adminStore.hasAdmins()){return ctx.send({error:`no_admins_setup`})}return ctx.send({authUrl:getOauthRedirectUrl(ctx,"login",origin)})}var modulename47="WebServer:AuthProviderCallback";var console58=console_default(modulename47);var bodySchema4=z.object({redirectUri:z.string()});async function AuthProviderCallback(ctx){const schemaRes=bodySchema4.safeParse(ctx.request.body);if(!schemaRes.success){return ctx.send({errorTitle:"Invalid request body",errorMessage:schemaRes.error.message})}const{redirectUri}=schemaRes.data;const callbackResp=await handleOauthCallback(ctx,redirectUri);if("errorCode"in callbackResp||"errorTitle"in callbackResp){return ctx.send(callbackResp)}const userInfo=callbackResp;const fivemIdentifier=getIdFromOauthNameid(userInfo.nameid);if(!fivemIdentifier){return ctx.send({errorTitle:"Invalid nameid identifier.",errorMessage:`Could not extract the user identifier from the URL below. Please report this to the txAdmin dev team.
${userInfo.nameid.toString()}`})}try{const vaultAdmin=txCore.adminStore.getAdminByIdentifiers([fivemIdentifier]);if(!vaultAdmin){ctx.sessTools.destroy();return ctx.send({errorCode:"not_admin",errorContext:{identifier:fivemIdentifier,name:userInfo.name,profile:userInfo.profile}})}const sessData={type:"cfxre",username:vaultAdmin.name,csrfToken:txCore.adminStore.genCsrfToken(),expiresAt:Date.now()+864e5,identifier:fivemIdentifier};ctx.sessTools.set({auth:sessData});if(userInfo.picture){txCore.cacheStore.set(`admin:picture:${vaultAdmin.name}`,userInfo.picture)}const authedAdmin=new AuthedAdmin(vaultAdmin,sessData.csrfToken);authedAdmin.logAction(`logged in from ${ctx.ip} via cfxre`);txCore.metrics.txRuntime.loginOrigins.count(ctx.txVars.hostType);txCore.metrics.txRuntime.loginMethods.count("citizenfx");return ctx.send(authedAdmin.getAuthData())}catch(error){ctx.sessTools.destroy();console58.verbose.error(`Failed to login: ${error.message}`);return ctx.send({errorTitle:"Failed to login:",errorMessage:error.message})}}var modulename48="WebServer:AuthVerifyPassword";var console59=console_default(modulename48);var bodySchema5=z.object({username:z.string().trim(),password:z.string().trim()});async function AuthVerifyPassword(ctx){const{uiVersion}=ctx.request.query;if(uiVersion&&uiVersion!==txEnv.txaVersion){return ctx.send({error:`refreshToUpdate`})}const schemaRes=bodySchema5.safeParse(ctx.request.body);if(!schemaRes.success){return ctx.send({error:`Invalid request body: ${schemaRes.error.message}`})}const postBody=schemaRes.data;if(!txCore.adminStore.hasAdmins()){return ctx.send({error:`no_admins_setup`})}try{const vaultAdmin=txCore.adminStore.getAdminByName(postBody.username);if(!vaultAdmin){console59.warn(`Wrong username from: ${ctx.ip}`);return ctx.send({error:"Wrong username or password!"})}if(!VerifyPasswordHash(postBody.password,vaultAdmin.password_hash)){console59.warn(`Wrong password from: ${ctx.ip}`);return ctx.send({error:"Wrong username or password!"})}const sessData={type:"password",username:vaultAdmin.name,password_hash:vaultAdmin.password_hash,expiresAt:false,csrfToken:txCore.adminStore.genCsrfToken()};ctx.sessTools.set({auth:sessData});txCore.logger.admin.write(vaultAdmin.name,`logged in from ${ctx.ip} via password`);txCore.metrics.txRuntime.loginOrigins.count(ctx.txVars.hostType);txCore.metrics.txRuntime.loginMethods.count("password");const authedAdmin=new AuthedAdmin(vaultAdmin,sessData.csrfToken);return ctx.send(authedAdmin.getAuthData())}catch(error){console59.warn(`Failed to authenticate ${postBody.username} with error: ${error.message}`);console59.verbose.dir(error);return ctx.send({error:"Error autenticating admin."})}}var modulename49="WebServer:AuthChangePassword";var console60=console_default(modulename49);var bodySchema6=z.object({oldPassword:z.string().optional(),newPassword:z.string()});async function AuthChangePassword(ctx){var _a13;const schemaRes=bodySchema6.safeParse(ctx.request.body);if(!schemaRes.success){return ctx.send({error:`Invalid request body: ${schemaRes.error.message}`})}const{newPassword,oldPassword}=schemaRes.data;if(newPassword.trim()!==newPassword){return ctx.send({error:"Your password either starts or ends with a space, which was likely an accident. Please remove it and try again."})}if(newPassword.length<consts_default.adminPasswordMinLength||newPassword.length>consts_default.adminPasswordMaxLength){return ctx.send({error:"Invalid new password length."})}const vaultAdmin=txCore.adminStore.getAdminByName(ctx.admin.name);if(!vaultAdmin)throw new Error("Wait, what? Where is that admin?");if(!ctx.admin.isTempPassword){if(!oldPassword||!VerifyPasswordHash(oldPassword,vaultAdmin.password_hash)){return ctx.send({error:"Wrong current password."})}}try{const newHash=await txCore.adminStore.editAdmin(ctx.admin.name,newPassword);const currSess=ctx.sessTools.get();if(((_a13=currSess==null?void 0:currSess.auth)==null?void 0:_a13.type)==="password"){ctx.sessTools.set({auth:{...currSess.auth,password_hash:newHash}})}ctx.admin.logAction("Changing own password.");return ctx.send({success:true})}
You can also leave it blank.`})}discordData={id:discordId.substring(8),identifier:discordId}}const vaultAdmin=txCore.adminStore.getAdminByName(ctx.admin.name);if(!vaultAdmin)throw new Error("Wait, what? Where is that admin?");try{await txCore.adminStore.editAdmin(ctx.admin.name,null,citizenfxData,discordData);ctx.admin.logAction("Changing own identifiers.");return ctx.send({success:true})}catch(error){return ctx.send({error:error.message})}}var modulename54="WebServer:AdminManagerPage";var console65=console_default(modulename54);async function AdminManagerPage(ctx){if(!ctx.admin.hasPermission("manage.admins")){return ctx.utils.render("main/message",{message:"You don't have permission to view this page."})}const admins=txCore.adminStore.getAdminsList().map(admin=>{let perms;if(admin.master==true){perms="master account"}else if(admin.permissions.includes("all_permissions")){perms="all permissions"}else if(admin.permissions.length!==1){perms=`${admin.permissions.length} permissions`}else{perms="1 permission"}const isSelf=ctx.admin.name.toLowerCase()===admin.name.toLowerCase();return{hasCitizenFX:admin.providers.includes("citizenfx"),hasDiscord:admin.providers.includes("discord"),name:admin.name,perms,isSelf,disableEdit:!ctx.admin.isMaster&&admin.master,disableDelete:admin.master||isSelf}});const renderData={headerTitle:"Admin Manager",admins};return ctx.utils.render("main/adminManager",renderData)}var modulename55="WebServer:AdminManagerGetModal";var console66=console_default(modulename55);var dangerousPerms=["all_permissions","manage.admins","console.write","settings.write"];var getPerms=(checkPerms,allPermissions)=>{const permsGeneral=[];const permsMenu=[];for(const[id,desc]of allPermissions){const bucket=id.startsWith("players.")||id.startsWith("menu.")?permsGeneral:permsMenu;bucket.push({id,desc,checked:checkPerms.includes(id)?"checked":"",dangerous:dangerousPerms.includes(id)})}return[permsGeneral,permsMenu]};async function AdminManagerGetModal(ctx){if(typeof ctx.params.modalType!=="string"){return ctx.utils.error(400,"Invalid Request")}const modalType=ctx.params.modalType;if(!ctx.admin.testPermission("manage.admins",modulename55)){return ctx.send({type:"danger",message:"You don't have permission to execute this action."})}let isNewAdmin;if(modalType=="add"){isNewAdmin=true}else if(modalType=="edit"){isNewAdmin=false}else{return ctx.send({type:"danger",message:"Unknown modalType."})}const allPermissions=Object.entries(txCore.adminStore.getPermissionsList());if(isNewAdmin){const[permsGeneral2,permsMenu2]=getPerms([],allPermissions);const renderData2={isNewAdmin:true,username:"",citizenfx_id:"",discord_id:"",permsGeneral:permsGeneral2,permsMenu:permsMenu2};return ctx.utils.render("parts/adminModal",renderData2)}if(typeof ctx.request.body.name!=="string"){return ctx.utils.error(400,"Invalid Request - missing parameters")}const name=ctx.request.body.name.trim();const admin=txCore.adminStore.getAdminByName(name);if(!admin)return ctx.send("Admin not found");if(!ctx.admin.isMaster&&admin.master){return ctx.send("You cannot edit an admin master.")}const[permsGeneral,permsMenu]=getPerms(admin.permissions,allPermissions);const renderData={isNewAdmin:false,username:admin.name,citizenfx_id:admin.providers.citizenfx?admin.providers.citizenfx.id:"",discord_id:admin.providers.discord?admin.providers.discord.id:"",permsGeneral,permsMenu};return ctx.utils.render("parts/adminModal",renderData)}var import_nolookalikes2=__toESM(require_nolookalikes(),1);var modulename56="WebServer:AdminManagerActions";var console67=console_default(modulename56);var nanoid3=customAlphabet(import_nolookalikes2.default,20);var nameRegexDesc="up to 20 characters containing only letters, numbers and the characters `_.-`";var cfxHttpReqOptions2={timeout:{request:6e3}};async function AdminManagerActions(ctx){var _a13;if(typeof((_a13=ctx.params)==null?void 0:_a13.action)!=="string"){return ctx.utils.error(400,"Invalid Request")}const action=ctx.params.action;if(!ctx.admin.testPermission("manage.admins",modulename56)){return ctx.send({type:"danger",message:"You
${nameRegexDesc}`})}let citizenfxData;if(citizenfxID.length){try{if(consts_default.validIdentifiers.fivem.test(citizenfxID)){const id=citizenfxID.split(":")[1];const res=await got_default(`https://policy-live.fivem.net/api/getUserInfo/${id}`,cfxHttpReqOptions2).json();if(!res.username||!res.username.length){return ctx.send({type:"danger",message:"Invalid CitizenFX ID1"})}citizenfxData={id:res.username,identifier:citizenfxID}}else if(consts_default.regexValidFivemUsername.test(citizenfxID)){const res=await got_default(`https://forum.cfx.re/u/${citizenfxID}.json`,cfxHttpReqOptions2).json();if(!res.user||typeof res.user.id!=="number"){return ctx.send({type:"danger",message:"Invalid CitizenFX ID2"})}citizenfxData={id:citizenfxID,identifier:`fivem:${res.user.id}`}}else{return ctx.send({type:"danger",message:"Invalid CitizenFX ID3"})}}catch(error){console67.error(`Failed to resolve CitizenFX ID to game identifier with error: ${error.message}`)}}let discordData;if(discordID.length){if(!consts_default.validIdentifierParts.discord.test(discordID)){return ctx.send({type:"danger",message:"Invalid Discord ID"})}discordData={id:discordID,identifier:`discord:${discordID}`}}if(!ctx.admin.isMaster&&!ctx.admin.permissions.includes("all_permissions")){const deniedPerms=permissions.filter(x=>!ctx.admin.permissions.includes(x));if(deniedPerms.length){return ctx.send({type:"danger",message:`You cannot give permissions you do not have:<br>${deniedPerms.join(", ")}`})}}try{await txCore.adminStore.addAdmin(name,citizenfxData,discordData,password,permissions);ctx.admin.logAction(`Adding user '${name}'.`);return ctx.send({type:"showPassword",password})}catch(error){return ctx.send({type:"danger",message:error.message})}}async function handleEdit(ctx){if(typeof ctx.request.body.name!=="string"||typeof ctx.request.body.citizenfxID!=="string"||typeof ctx.request.body.discordID!=="string"||ctx.request.body.permissions===void 0){return ctx.utils.error(400,"Invalid Request - missing parameters")}const name=ctx.request.body.name.trim();const citizenfxID=ctx.request.body.citizenfxID.trim();const discordID=ctx.request.body.discordID.trim();if(ctx.admin.name.toLowerCase()===name.toLowerCase()){return ctx.send({type:"danger",message:"(ERR0) You cannot edit yourself."})}let permissions;if(Array.isArray(ctx.request.body.permissions)){permissions=ctx.request.body.permissions.filter(x=>typeof x==="string");if(permissions.includes("all_permissions"))permissions=["all_permissions"]}else{permissions=[]}let citizenfxData;if(citizenfxID.length){try{if(consts_default.validIdentifiers.fivem.test(citizenfxID)){const id=citizenfxID.split(":")[1];const res=await got_default(`https://policy-live.fivem.net/api/getUserInfo/${id}`,cfxHttpReqOptions2).json();if(!res.username||!res.username.length){return ctx.send({type:"danger",message:"(ERR1) Invalid CitizenFX ID"})}citizenfxData={id:res.username,identifier:citizenfxID}}else if(consts_default.regexValidFivemUsername.test(citizenfxID)){const res=await got_default(`https://forum.cfx.re/u/${citizenfxID}.json`,cfxHttpReqOptions2).json();if(!res.user||typeof res.user.id!=="number"){return ctx.send({type:"danger",message:"(ERR2) Invalid CitizenFX ID"})}citizenfxData={id:citizenfxID,identifier:`fivem:${res.user.id}`}}else{return ctx.send({type:"danger",message:"(ERR3) Invalid CitizenFX ID"})}}catch(error){console67.error(`Failed to resolve CitizenFX ID to game identifier with error: ${error.message}`)}}let discordData;if(discordID.length){if(!consts_default.validIdentifierParts.discord.test(discordID)){return ctx.send({type:"danger",message:"Invalid Discord ID"})}discordData={id:discordID,identifier:`discord:${discordID}`}}const admin=txCore.adminStore.getAdminByName(name);if(!admin)return ctx.send({type:"danger",message:"Admin not found."});if(!ctx.admin.isMaster&&admin.master){return ctx.send({type:"danger",message:"You cannot edit an admin master."})}if(permissions&&!ctx.admin.isMaster&&!ctx.admin.permissions.includes("all_permissions")){const deniedPerms=permissions.filter(x=>!ctx.admin.permissions.includes(x));if(deniedPerms.
${error.message}`})}if(result2.errors){return ctx.send({type:"danger",markdown:true,message:`**Cannot save \`server.cfg\` due to error(s) in your config file(s):**
${result2.errors}`})}if(result2.warnings){return ctx.send({type:"warning",markdown:true,message:`**File saved, but there are warnings you should pay attention to:**
${result2.warnings}`})}return ctx.send({type:"success",markdown:true,message:"**File saved.**"})}var import_fs_extra4=__toESM(require_lib2(),1);var modulename59="WebServer:DeployerStepper";var console70=console_default(modulename59);async function DeployerStepper(ctx){var _a13;if(!ctx.admin.hasPermission("master")){return ctx.utils.render("main/message",{message:"You need to be the admin master to use the deployer."})}if(txManager.configState==="setup"){return ctx.utils.legacyNavigateToPage("/server/setup")}else if(txManager.configState!=="deployer"){return ctx.utils.legacyNavigateToPage("/")}else if(!((_a13=txManager.deployer)==null?void 0:_a13.step)){throw new Error(`txManager.configState is Deployer but txManager.deployer is not defined`)}const renderData={step:txManager.deployer.step,serverProfile:txEnv.profile,deploymentID:txManager.deployer.deploymentID,requireDBConfig:false,defaultLicenseKey:"",recipe:void 0,defaults:{}};if(txManager.deployer.step==="review"){renderData.recipe={isTrustedSource:txManager.deployer.isTrustedSource,name:txManager.deployer.recipe.name,author:txManager.deployer.recipe.author,description:txManager.deployer.recipe.description,raw:txManager.deployer.recipe.raw}}else if(txManager.deployer.step==="input"){renderData.defaultLicenseKey=txDevEnv.CFXKEY??"";renderData.requireDBConfig=txManager.deployer.recipe.requireDBConfig;if(convars.deployerDefaults){renderData.defaults={autofilled:true,license:convars.deployerDefaults.license??"",mysqlHost:convars.deployerDefaults.mysqlHost??"localhost",mysqlPort:convars.deployerDefaults.mysqlPort??"3306",mysqlUser:convars.deployerDefaults.mysqlUser??"root",mysqlPassword:convars.deployerDefaults.mysqlPassword??"",mysqlDatabase:convars.deployerDefaults.mysqlDatabase??txManager.deployer.deploymentID}}else{renderData.defaults={autofilled:false,license:txDevEnv.CFXKEY??"",mysqlHost:"localhost",mysqlUser:"root",mysqlPort:"3306",mysqlPassword:"",mysqlDatabase:txManager.deployer.deploymentID}}const knownVarDescriptions={steam_webApiKey:"The Steam Web API Key is used to authenticate players when they join.<br/>\nYou can get one at https://steamcommunity.com/dev/apikey."};const recipeVars=txManager.deployer.getRecipeVars();renderData.inputVars=Object.keys(recipeVars).map(name=>{return{name,value:recipeVars[name],description:knownVarDescriptions[name]||""}})}else if(txManager.deployer.step==="run"){renderData.deployPath=txManager.deployer.deployPath}else if(txManager.deployer.step==="configure"){const errorMessage=`# server.cfg Not Found!
# This probably means you deleted it before pressing "Next".
# Press cancel and start the deployer again,
# or insert here the server.cfg contents.
# (°° `;try{renderData.serverCFG=await import_fs_extra4.default.readFile(`${txManager.deployer.deployPath}/server.cfg`,"utf8");if(renderData.serverCFG=="#save_attempt_please_ignore"||!renderData.serverCFG.length){renderData.serverCFG=errorMessage}else if(renderData.serverCFG.length>10240){renderData.serverCFG=`# This recipe created a ./server.cfg above 10kb, meaning its probably the wrong data.
Make sure everything is correct in the recipe and try again.`}}catch(error){console70.verbose.dir(error);renderData.serverCFG=errorMessage}}else{return ctx.utils.render("main/message",{message:"Unknown Deployer step, please report this bug and restart txAdmin."})}return ctx.utils.render("standalone/deployer",renderData)}var modulename60="WebServer:DeployerStatus";var console71=console_default(modulename60);async function DeployerStatus(ctx){if(!ctx.admin.hasPermission("all_permissions")){return ctx.send({success:false,refresh:true})}if(txManager.deployer==null){return ctx.send({success:false,refresh:true})}const outData={progress:txManager.deployer.progress,log:txManager.deployer.getDeployerLog()};if(txManager.deployer.step=="configure"){outData.status="done"}else if(txManager.deployer.deployFailed){outData.status="failed"}else{outData.status="running"}return ctx.send(outData)}var import_node_path14=__toESM(require("node:path"),1);var import_promise2=__toESM(require_promise2(),1);var modulename61="WebServer:DeployerActions";var console72=console_default(modulename61);var isUndefined4=x=>x===void 0;async function DeployerActions(ctx){if(isUndefined4(ctx.params.action)){return ctx.utils.error(400,"Invalid Request")}const action=ctx.params.action;if(!ctx.admin.testPermission("master",modulename61)){return ctx.send({success:false,refresh:true})}if(txManager.deployer==null){return ctx.send({success:false,refresh:true})}if(action=="confirmRecipe"){return await handleConfirmRecipe(ctx)}else if(action=="setVariables"){return await handleSetVariables(ctx)}else if(action=="commit"){return await handleSaveConfig(ctx)}else if(action=="cancel"){return await handleCancel(ctx)}else{return ctx.send({type:"danger",message:"Unknown setup action."})}}async function handleConfirmRecipe(ctx){if(isUndefined4(ctx.request.body.recipe)){return ctx.utils.error(400,"Invalid Request - missing parameters")}const userEditedRecipe=ctx.request.body.recipe;try{ctx.admin.logAction("Setting recipe.");await txManager.deployer.confirmRecipe(userEditedRecipe)}catch(error){return ctx.send({type:"danger",message:error.message})}return ctx.send({success:true})}async function handleSetVariables(ctx){var _a13;if(isUndefined4(ctx.request.body.svLicense)){return ctx.utils.error(400,"Invalid Request - missing parameters")}const userVars=cloneDeep_default(ctx.request.body);if(!consts_default.regexSvLicenseNew.test(userVars.svLicense)&&!consts_default.regexSvLicenseOld.test(userVars.svLicense)){return ctx.send({type:"danger",message:"The Server License does not appear to be valid."})}if(txManager.deployer.recipe.steamRequired&&(typeof userVars.steam_webApiKey!=="string"||userVars.steam_webApiKey.length<24)){return ctx.send({type:"danger",message:"This recipe requires steam_webApiKey to be set and valid."})}if(typeof userVars.dbDelete!=="undefined"){try{userVars.dbPort=parseInt(userVars.dbPort);if(isNaN(userVars.dbPort)){return ctx.send({type:"danger",message:"The database port is invalid (non-integer). The default is 3306."})}const mysqlOptions={host:userVars.dbHost,port:userVars.dbPort,user:userVars.dbUsername,password:userVars.dbPassword,connectTimeout:5e3};await import_promise2.default.createConnection(mysqlOptions)}catch(error){let outMessage=(error==null?void 0:error.message)??"Unknown error occurred.";if((error==null?void 0:error.code)==="ECONNREFUSED"){let specificError=txEnv.isWindows?"If you do not have a database installed, you can download and run XAMPP.":"If you do not have a database installed, you must download and run MySQL or MariaDB.";if(userVars.dbPort!==3306){specificError+="<br>\n<b>You are not using the default DB port 3306, make sure it is correct!</b>"}outMessage=`${error==null?void 0:error.message}<br>
${specificError}`}else if((_a13=error.message)==null?void 0:_a13.includes("auth_gssapi_client")){outMessage=`Your database does not accept the required authentication method. Please update your MySQL/MariaDB server and try again.`}return ctx.send({type:"danger",message:`<b>Database connection failed:</b> ${outMessage}`})}userVars.dbDelete=userVars.dbDelete==="true";const dbFullHost=userVars.dbPort===3306?userVars.dbHost:`${userVars.dbHost}:${userVars.dbPort}`;userVars.dbConnectionString=userVars.dbPassword.length?`mysql://${userVars.dbUsername}:${userVars.dbPassword}@${dbFullHost}/${userVars.dbName}?charset=utf8mb4`:`mysql://${userVars.dbUsername}@${dbFullHost}/${userVars.dbName}?charset=utf8mb4`}userVars.maxClients=convars.deployerDefaults&&convars.deployerDefaults.maxClients?convars.deployerDefaults.maxClients:48;if(convars.forceInterface||convars.forceFXServerPort){const comment=`# ${convars.providerName}: do not modify!`;const endpointIface=convars.forceInterface??"0.0.0.0";const endpointPort=convars.forceFXServerPort??30120;userVars.serverEndpoints=[`endpoint_add_tcp "${endpointIface}:${endpointPort}" ${comment}`,`endpoint_add_udp "${endpointIface}:${endpointPort}" ${comment}`].join("\n")}else{userVars.serverEndpoints=['endpoint_add_tcp "0.0.0.0:30120"','endpoint_add_udp "0.0.0.0:30120"'].join("\n")}const admin=txCore.adminStore.getAdminByName(ctx.admin.name);if(!admin)return ctx.send({type:"danger",message:"Admin not found."});const addPrincipalLines=[];Object.keys(admin.providers).forEach(providerName2=>{if(admin.providers[providerName2].identifier){addPrincipalLines.push(`add_principal identifier.${admin.providers[providerName2].identifier} group.admin #${ctx.admin.name}`)}});userVars.addPrincipalsMaster=addPrincipalLines.length?addPrincipalLines.join("\n"):"# Deployer Note: this admin master has no identifiers to be automatically added.\n# add_principal identifier.discord:111111111111111111 group.admin #example";try{ctx.admin.logAction("Running recipe.");txManager.deployer.start(userVars)}catch(error){return ctx.send({type:"danger",message:error.message})}return ctx.send({success:true})}async function handleSaveConfig(ctx){var _a13,_b2,_c,_d;if(isUndefined4(ctx.request.body.serverCFG)){return ctx.utils.error(400,"Invalid Request - missing parameters")}const serverCFG=ctx.request.body.serverCFG;const cfgFilePath=import_node_path14.default.join(txManager.deployer.deployPath,"server.cfg");txCore.cacheStore.set("deployer:recipe",((_b2=(_a13=txManager.deployer)==null?void 0:_a13.recipe)==null?void 0:_b2.name)??"unknown");try{const result2=await validateModifyServerConfig(serverCFG,cfgFilePath,txManager.deployer.deployPath);if(result2.errors){return ctx.send({type:"danger",success:false,markdown:true,message:`**Cannot save \`server.cfg\` due to error(s) in your config file(s):**
${result2.errors}`})}}catch(error){return ctx.send({type:"danger",success:false,markdown:true,message:`**Failed to save \`server.cfg\` with error:**
${error.message}`})}let onesync2=SYM_RESET_CONFIG;if(typeof((_d=(_c=txManager.deployer)==null?void 0:_c.recipe)==null?void 0:_d.onesync)==="string"&&txManager.deployer.recipe.onesync.length){onesync2=txManager.deployer.recipe.onesync}try{txCore.configStore.saveConfigs({server:{dataPath:slash(import_node_path14.default.normalize(txManager.deployer.deployPath)),cfgPath:"server.cfg",onesync:onesync2}},ctx.admin.name)}catch(error){console72.warn(`[${ctx.admin.name}] Error changing fxserver settings via deployer.`);console72.verbose.dir(error);return ctx.send({type:"danger",markdown:true,message:`**Error saving the configuration file:** ${error.message}`})}ctx.admin.logAction("Completed and committed server deploy.");if(!txCore.fxRunner.isIdle){ctx.admin.logCommand("STOP SERVER");await txCore.fxRunner.killServer("new server deployed",ctx.admin.name,true)}const spawnError=await txCore.fxRunner.spawnServer(false);if(spawnError!==null){return ctx.send({type:"danger",markdown:true,message:`Config file saved, but failed to start server with error:
${spawnError}`})}else{txManager.deployer=null;txCore.webServer.webSocket.pushRefresh("status");return ctx.send({success:true})}}async function handleCancel(ctx){txManager.deployer=null;txCore.webServer.webSocket.pushRefresh("status");return ctx.send({success:true})}var modulename62="WebServer:GetSettingsConfigs";var console73=console_default(modulename62);async function GetSettingsConfigs(ctx){var _a13,_b2;const sendTypedResp2=data=>ctx.send(data);if(!ctx.admin.testPermission("settings.view",modulename62)){return sendTypedResp2({error:"You do not have permission to view the settings."})}const locales=Object.keys(localeMap_default).map(code=>({code,label:localeMap_default[code].$meta.label}));locales.sort((a,b)=>a.label.localeCompare(b.label));const outData={locales,changelog:txCore.configStore.getChangelog(),storedConfigs:txCore.configStore.getStoredConfig(),defaultConfigs:ConfigStore.SchemaDefaults,forceQuietMode:convars.forceQuietMode};if(!ctx.admin.hasPermission("settings.write")){const toRedact=outData.storedConfigs;if((_a13=outData.storedConfigs.server)==null?void 0:_a13.startupArgs){toRedact.server.startupArgs=redactStartupSecrets(outData.storedConfigs.server.startupArgs)}if((_b2=outData.storedConfigs.discordBot)==null?void 0:_b2.token){toRedact.discordBot.token="[redacted by txAdmin]"}}return sendTypedResp2(outData)}var import_promises16=__toESM(require("node:fs/promises"),1);var import_node_path15=__toESM(require("node:path"),1);var modulename63="WebServer:SettingsPage";var console74=console_default(modulename63);var cardNamesMap={general:"General",fxserver:"FXServer",bans:"Bans",whitelist:"Whitelist",discord:"Discord","game-menu":"Game Menu","game-notifications":"Game Notifications"};var validCardIds=Object.keys(cardNamesMap);var paramsSchema2=z.object({card:z.enum(validCardIds)});var bodySchema9=z.object({}).passthrough();var cleanPath3=x=>slash(import_node_path15.default.normalize(x));async function SaveSettingsConfigs(ctx){const sendTypedResp2=data=>ctx.send(data);if(!ctx.admin.testPermission("settings.write",modulename63)){return sendTypedResp2({type:"error",msg:"You don't have permission to execute this action."})}const paramsSchemaRes=paramsSchema2.safeParse(ctx.params);const bodySchemaRes=bodySchema9.safeParse(ctx.request.body);if(!paramsSchemaRes.success||!bodySchemaRes.success){return sendTypedResp2({type:"error",md:true,title:"Invalid Request",msg:fromError(paramsSchemaRes.error??bodySchemaRes.error,{prefix:null}).message})}const cardId=paramsSchemaRes.data.card;const inputConfig=bodySchemaRes.data;const cardName=cardNamesMap[ctx.params.card]??"UNKNOWN";let handlerResp={processedConfig:inputConfig};try{if(cardId==="general"){handlerResp=await handleGeneralCard(inputConfig,sendTypedResp2)}else if(cardId==="fxserver"){handlerResp=await handleFxserverCard(inputConfig,sendTypedResp2)}else if(cardId==="discord"){handlerResp=await handleDiscordCard(inputConfig,sendTypedResp2)}}catch(error){return sendTypedResp2({type:"error",md:true,title:`Error processing the ${cardName} changes.`,msg:error.message})}if(!handlerResp)return;try{const changes=txCore.configStore.saveConfigs(ctx.request.body,ctx.admin.name);if(changes.hasMatch(["server.dataPath","server.cfgPath"])){txCore.webServer.webSocket.pushRefresh("status")}return sendTypedResp2({type:"success",msg:`${cardName} Settings saved!`,...(handlerResp==null?void 0:handlerResp.successToast)??{},stored:txCore.configStore.getStoredConfig(),changelog:txCore.configStore.getChangelog()})}catch(error){const cardName2=cardNamesMap[ctx.params.card]??"UNKNOWN";return sendTypedResp2({type:"error",md:true,title:`Error saving the ${cardName2} changes.`,msg:error.message})}}var handleGeneralCard=async(inputConfig,sendTypedResp2)=>{var _a13;if(((_a13=inputConfig.general)==null?void 0:_a13.language)===void 0)throw new Error(`Unexpected data for the 'general' card.`);if(inputConfig.general.language==="custom"){try{const raw=await import_promises16.default.readFile(txCore.translator.customLocalePath,"utf8");if(!raw.length)throw new Error("The `locale.json` file is empty.");const
\`${txCore.translator.customLocalePath}\``}else if(error.message.includes("JSON")){msg="The custom language file contains invalid JSON."}else if(error instanceof z.ZodError){msg=fromError(error,{prefix:"Invalid Locale Metadata"}).message}}return sendTypedResp2({type:"error",title:"Custom Language Error",md:true,msg})}}return{processedConfig:inputConfig}};var handleFxserverCard=async(inputConfig,sendTypedResp2)=>{var _a13,_b2,_c,_d,_e;if(typeof((_a13=inputConfig.server)==null?void 0:_a13.dataPath)!=="string"||!((_b2=inputConfig.server)==null?void 0:_b2.dataPath.length)){throw new Error(`Unexpected data for the 'fxserver' card.`)}const dataPath3=inputConfig.server.dataPath;try{const isValid2=await isValidServerDataPath(dataPath3);if(!isValid2)throw new Error(`unexpected isValidServerDataPath response`)}catch(error){try{const potentialFix=await findPotentialServerDataPaths(dataPath3);if(potentialFix){return sendTypedResp2({type:"error",title:"Server Data Folder Error",md:true,msg:`The path provided is not valid.
Did you mean this path?
\`${cleanPath3(potentialFix)}\``})}}catch(error2){}return sendTypedResp2({type:"error",title:"Server Data Folder Error",md:true,msg:error.message})}let cfgPath2=txConfig.server.cfgPath;if(((_c=inputConfig.server)==null?void 0:_c.cfgPath)!==void 0){const res=ConfigStore.Schema.server.cfgPath.validator.safeParse(inputConfig.server.cfgPath);if(!res.success){return sendTypedResp2({type:"error",title:"Invalid CFG Path",md:true,msg:fromError(res.error,{prefix:null}).message})}cfgPath2=res.data}try{cfgPath2=resolveCFGFilePath(cfgPath2,dataPath3);const cfgFileStat=await import_promises16.default.stat(cfgPath2);if(!cfgFileStat.isFile()){throw new Error("The path provided is not a file")}}catch(error){return sendTypedResp2({type:"error",title:"CFG Path Error",md:true,msg:getFsErrorMdMessage(error,cleanPath3(cfgPath2))})}if(typeof((_d=inputConfig.server)==null?void 0:_d.dataPath)==="string"){inputConfig.server.dataPath=cleanPath3(inputConfig.server.dataPath)}if(typeof((_e=inputConfig.server)==null?void 0:_e.cfgPath)==="string"){inputConfig.server.cfgPath=cleanPath3(inputConfig.server.cfgPath)}return{processedConfig:inputConfig,successToast:{type:"success",title:"FXServer Settings Saved!",msg:"You need to restart the server for the changes to take effect."}}};var handleDiscordCard=async(inputConfig,sendTypedResp2)=>{var _a13;if(!inputConfig.discordBot)throw new Error(`Unexpected data for the 'discord' card.`);if(typeof inputConfig.discordBot.embedJson==="string"||typeof inputConfig.discordBot.embedConfigJson==="string"){try{generateStatusMessage(inputConfig.discordBot.embedJson??txConfig.discordBot.embedJson,inputConfig.discordBot.embedConfigJson??txConfig.discordBot.embedConfigJson)}catch(error){return sendTypedResp2({type:"error",title:"Embed validation failed:",md:true,msg:error.message})}}if(!((_a13=inputConfig.discordBot)==null?void 0:_a13.enabled)){await txCore.discordBot.attemptBotReset(false);return{processedConfig:inputConfig}}const baseError={type:"error",title:"Discord Bot Error",md:true};const schemas=ConfigStore.Schema.discordBot;const validationError=getSchemaChainError([[schemas.enabled,inputConfig.discordBot.enabled],[schemas.token,inputConfig.discordBot.token],[schemas.guild,inputConfig.discordBot.guild],[schemas.warningsChannel,inputConfig.discordBot.warningsChannel]]);if(validationError){return sendTypedResp2({...baseError,msg:validationError})}if(!inputConfig.discordBot.token||!inputConfig.discordBot.guild){return sendTypedResp2({...baseError,msg:"Missing required fields to enable the bot."})}let successMsg;try{successMsg=await txCore.discordBot.attemptBotReset({enabled:true,token:inputConfig.discordBot.token,guild:inputConfig.discordBot.guild,warningsChannel:inputConfig.discordBot.warningsChannel})}catch(error){const errorCode=error.code;let extraContext="";if(errorCode==="DisallowedIntents"||errorCode===4014){extraContext=`**The bot requires the \`GUILD_MEMBERS\` intent.**
- Go to the [Discord Dev Portal](https://discord.com/developers/applications)
- Navigate to \`Bot > Privileged Gateway Intents\`.
- Enable the \`GUILD_MEMBERS\` intent.
- Press save on the developer portal.
- Go to the \`txAdmin > Settings > Discord Bot\` and press save.`}else if(errorCode==="CustomNoGuild"){const inviteUrl="clientId"in error?`https://discord.com/oauth2/authorize?client_id=${error.clientId}&scope=bot&permissions=0`:`https://discordapi.com/permissions.html#0`;extraContext=`**This usually mean one of the issues below:**
- **Wrong server ID:** read the description of the server ID setting for more information.
- **Bot is not in the server:** you need to [INVITE THE BOT](${inviteUrl}) to join the server.
- **Wrong bot:** you may be using the token of another discord bot.`}else if(errorCode==="DangerousPermission"){extraContext=`You need to remove the permissions listed above to be able to enable this bot.
This should be done in the Discord Server role configuration page and not in the Dev Portal.
Check every single role that the bot has in the server.
Please keep in mind that:
- These permissions are dangerous because if the bot token leaks, an attacker can cause permanent damage to your server.
- No bot should have more permissions than strictly needed, especially \`Administrator\`.
- You should never have multiple bots using the same token, create a new one for each bot.`}return sendTypedResp2({...baseError,title:"Error starting the bot:",msg:`${error.message}
${extraContext}`.trim()})}return{processedConfig:inputConfig,successToast:{type:"success",md:true,title:"FXServer Settings Saved!",msg:`${successMsg}
If _(and only if)_ the status embed is not being updated, check the \`System > Console Log\` page to look for embed errors.`}}};var modulename64="WebServer:GetBanTemplates";var console75=console_default(modulename64);async function GetBanTemplates(ctx){const sendTypedResp2=data=>ctx.send(data);return sendTypedResp2(txConfig.banlist.templates)}var modulename65="WebServer:SaveBanTemplates";var console76=console_default(modulename65);var bodySchema10=z.any().array();async function SaveBanTemplates(ctx){const sendTypedResp2=data=>ctx.send(data);if(!ctx.admin.testPermission("settings.write",modulename65)){return sendTypedResp2({error:"You do not have permission to change the settings."})}const schemaRes=bodySchema10.safeParse(ctx.request.body);if(!schemaRes.success){return sendTypedResp2({error:`Invalid request body: ${schemaRes.error.message}`})}const banTemplates=schemaRes.data;try{txCore.configStore.saveConfigs({banlist:{templates:banTemplates}},ctx.admin.name)}catch(error){console76.warn(`[${ctx.admin.name}] Error changing banTemplates settings.`);console76.verbose.dir(error);return sendTypedResp2({error:`Error saving the configuration file: ${error.message}`})}return sendTypedResp2({success:true})}var modulename66="WebServer:SettingsPage";var console77=console_default(modulename66);async function ResetServerDataPath(ctx){const sendTypedResp2=data=>ctx.send(data);if(!ctx.admin.testPermission("all_permissions",modulename66)){return sendTypedResp2({type:"error",msg:"You don't have permission to execute this action."})}if(!txCore.fxRunner.isIdle){ctx.admin.logCommand("STOP SERVER");txCore.fxRunner.killServer("new server set up",ctx.admin.name,false).catch(e=>{})}txManager.deployer=null;try{txCore.configStore.saveConfigs({server:{dataPath:SYM_RESET_CONFIG,cfgPath:SYM_RESET_CONFIG}},ctx.admin.name)}catch(error){console77.warn(`[${ctx.admin.name}] Error resetting server data settings.`);console77.verbose.dir(error);return sendTypedResp2({type:"error",md:true,title:`Error resetting the server data path.`,msg:error.message})}txCore.webServer.webSocket.pushRefresh("status");ctx.admin.logAction("Resetting server data settings.");return sendTypedResp2({type:"success",msg:"Server data path reset."})}var modulename67="WebServer:MasterActions:Page";var console78=console_default(modulename67);async function MasterActionsPage(ctx){const isMasterAdmin=ctx.admin.hasPermission("master");return ctx.utils.render("main/masterActions",{headerTitle:"Master Actions",isMasterAdmin,disableActions:isMasterAdmin&&ctx.txVars.isWebInterface?"":"disabled"})}var import_promises17=__toESM(require("node:fs/promises"),1);var modulename68="WebServer:MasterActions:GetBackup";var console79=console_default(modulename68);async function MasterActionsGet(ctx){if(!ctx.admin.testPermission("master",modulename68)){return ctx.utils.render("main/message",{message:"Only the master account has permission to view/use this page."})}if(!ctx.txVars.isWebInterface){return ctx.utils.render("main/message",{message:"This functionality cannot be used by the in-game menu, please use the web version of txAdmin."})}const dbPath=`${txEnv.profilePath}/data/playersDB.json`;let readFile4;try{readFile4=await import_promises17.default.readFile(dbPath)}catch(error){console79.error(`Could not read database file ${dbPath}.`);return ctx.utils.render("main/message",{message:`Failed to generate backup file with error: ${error.message}`})}ctx.attachment(`playersDB_${getTimeFilename()}.json`);ctx.body=readFile4;console79.log(`[${ctx.admin.name}] Downloading player database.`)}var modulename69="WebServer:MasterActions:Action";var console80=console_default(modulename69);async function MasterActionsAction(ctx){if(typeof ctx.params.action!=="string"){return ctx.send({error:"Invalid Request"})}const action=ctx.params.action;if(!ctx.admin.testPermission("master",modulename69)){return ctx.send({error:"Only the master account has permission to view/use this page."})}if(!ctx.txVars.isWebInterface){return ctx.send({error:"This functionality cannot be used by the in-game menu, please use the web version of
But it looks like <code>{{attempt}}</code> is correct. <br>
Do you want to use it instead?`;const attemptIsParent=import_node_path17.default.join(dataFolderPath,"..");if(import_fs_extra5.default.existsSync(import_node_path17.default.join(attemptIsParent,"resources"))){const message3=recoveryTemplate.replace("{{attempt}}",attemptIsParent);return ctx.send({success:false,message:message3,suggestion:attemptIsParent})}const attemptOutside=getPotentialServerDataFolders(import_node_path17.default.join(dataFolderPath,".."));if(attemptOutside.length>=1){const message3=recoveryTemplate.replace("{{attempt}}",attemptOutside[0]);return ctx.send({success:false,message:message3,suggestion:attemptOutside[0]})}if(dataFolderPath.includes("/resources")){const attemptRes=dataFolderPath.split("/resources")[0];if(import_fs_extra5.default.existsSync(import_node_path17.default.join(attemptRes,"resources"))){const message3=recoveryTemplate.replace("{{attempt}}",attemptRes);return ctx.send({success:false,message:message3,suggestion:attemptRes})}}const attemptInside=getPotentialServerDataFolders(dataFolderPath);if(attemptInside.length>=1){const message3=recoveryTemplate.replace("{{attempt}}",attemptInside[0]);return ctx.send({success:false,message:message3,suggestion:attemptInside[0]})}throw new Error("Couldn't locate or read a resources folder inside of the path provided.")}else{return ctx.send({success:true,detectedConfig:findLikelyCFGPath(dataFolderPath)})}}catch(error){return ctx.send({success:false,message:error.message})}}async function handleValidateCFGFile(ctx){if(isUndefined5(ctx.request.body.dataFolder)||isUndefined5(ctx.request.body.cfgFile)){return ctx.utils.error(400,"Invalid Request - missing parameters")}const dataFolderPath=slash(import_node_path17.default.normalize(ctx.request.body.dataFolder.trim()));const cfgFilePathNormalized=slash(import_node_path17.default.normalize(ctx.request.body.cfgFile.trim()));try{const result2=await validateFixServerConfig(cfgFilePathNormalized,dataFolderPath);if(result2.errors){const message3=`**The file path is correct, but there are error(s) in your config file(s):**
${result2.errors}`;return ctx.send({success:false,markdown:true,message:message3})}else{return ctx.send({success:true})}}catch(error){const message3=`Error:
${error.message}.`;return ctx.send({success:false,message:message3})}}async function handleSaveLocal(ctx){if(isUndefined5(ctx.request.body.name)||isUndefined5(ctx.request.body.dataFolder)||isUndefined5(ctx.request.body.cfgFile)){return ctx.utils.error(400,"Invalid Request - missing parameters")}const cfg={name:ctx.request.body.name.trim(),dataFolder:slash(import_node_path17.default.normalize(ctx.request.body.dataFolder+"/")),cfgFile:slash(import_node_path17.default.normalize(ctx.request.body.cfgFile))};try{const stat3=await import_promises18.default.stat(import_node_path17.default.join(cfg.dataFolder,"resources"));if(!stat3.isDirectory()){throw new Error("not a directory")}}catch(error){let msg=(error==null?void 0:error.message)??"unknown error";if((error==null?void 0:error.code)==="ENOENT"){msg="The server data folder does not exist."}return ctx.send({success:false,message:`<strong>Server Data Folder error:</strong> ${msg}`})}try{txCore.configStore.saveConfigs({general:{serverName:cfg.name},server:{dataPath:cfg.dataFolder,cfgPath:cfg.cfgFile}},ctx.admin.name)}catch(error){console82.warn(`[${ctx.admin.name}] Error changing global/fxserver settings via setup stepper.`);console82.verbose.dir(error);return ctx.send({type:"danger",markdown:true,message:`**Error saving the configuration file:**
${error.message}`})}txCore.cacheStore.set("deployer:recipe","none");ctx.admin.logAction("Changing global/fxserver settings via setup stepper.");if(!txCore.fxRunner.isIdle){ctx.admin.logCommand("STOP SERVER");await txCore.fxRunner.killServer("new server set up",ctx.admin.name,true)}const spawnError=await txCore.fxRunner.spawnServer(false);if(spawnError!==null){return ctx.send({success:false,markdown:true,message:spawnError})}else{return ctx.send({success:true})}}async function handleSaveDeployerImport(ctx){if(isUndefined5(ctx.request.body.name)||isUndefined5(ctx.request.body.isTrustedSource)||isUndefined5(ctx.request.body.recipeURL)||isUndefined5(ctx.request.body.targetPath)||isUndefined5(ctx.request.body.deploymentID)){return ctx.utils.error(400,"Invalid Request - missing parameters")}const isTrustedSource=ctx.request.body.isTrustedSource==="true";const serverName2=ctx.request.body.name.trim();const recipeURL=ctx.request.body.recipeURL.trim();const targetPath=slash(import_node_path17.default.normalize(ctx.request.body.targetPath+"/"));const deploymentID=ctx.request.body.deploymentID;let recipeText;try{recipeText=await got_default.get({url:recipeURL,timeout:{request:4500}}).text();if(typeof recipeText!=="string")throw new Error("This URL did not return a string.")}catch(error){return ctx.send({success:false,message:`Recipe download error: ${error.message}`})}try{txCore.configStore.saveConfigs({general:{serverName:serverName2}},ctx.admin.name)}catch(error){console82.warn(`[${ctx.admin.name}] Error changing global settings via setup stepper.`);console82.verbose.dir(error);return ctx.send({type:"danger",markdown:true,message:`**Error saving the configuration file:** ${error.message}`})}ctx.admin.logAction("Changing global settings via setup stepper and started Deployer.");try{txManager.startDeployer(recipeText,deploymentID,targetPath,isTrustedSource,{serverName:serverName2});txCore.webServer.webSocket.pushRefresh("status")}catch(error){return ctx.send({success:false,message:error.message})}return ctx.send({success:true})}async function handleSaveDeployerCustom(ctx){if(isUndefined5(ctx.request.body.name)||isUndefined5(ctx.request.body.targetPath)||isUndefined5(ctx.request.body.deploymentID)){return ctx.utils.error(400,"Invalid Request - missing parameters")}const serverName2=ctx.request.body.name.trim();const targetPath=slash(import_node_path17.default.normalize(ctx.request.body.targetPath+"/"));const deploymentID=ctx.request.body.deploymentID;try{txCore.configStore.saveConfigs({general:{serverName:serverName2}},ctx.admin.name)}catch(error){console82.warn(`[${ctx.admin.name}] Error changing global settings via setup stepper.`);console82.verbose.dir(error);return ctx.send({type:"danger",markdown:true,message:`**Error saving the configuration file:** ${error.message}`})}ctx.admin.logAction("Changing global settings via setup stepper and started Deployer.");const customMetaData={author:ctx.admin.name,serverName:serverName2};try{txManager.startDeployer(false,deploymentID,targetPath,false,customMetaData);txCore.webServer.webSocket.pushRefresh("status")}catch(error){return ctx.send({success:false,message:error.message})}return ctx.send({success:true})}var modulename72="WebServer:FXServerCommands";var console83=console_default(modulename72);var delay3=async ms=>{return new Promise(resolve=>setTimeout(resolve,ms))};async function FXServerCommands(ctx){var _a13;if(typeof ctx.request.body.action==="undefined"||typeof ctx.request.body.parameter==="undefined"){return ctx.send({type:"error",msg:"Invalid request."})}const action=ctx.request.body.action;const parameter=ctx.request.body.parameter;if(!((_a13=txCore.fxRunner.child)==null?void 0:_a13.isAlive)){return ctx.send({type:"error",msg:"The server is not running."})}const unsafeActions=["restart_res","start_res","ensure_res"];if(unsafeActions.includes(action)&&parameter.includes("runcode")){return ctx.send({type:"error",msg:'The resource "runcode" might be unsafe. <br> If you know what you are doing, run it via the Live Console.'})}if(action=="profile_monitor"){if(!ensurePermission2(ct
<div style="
background-color: rgba(30, 30, 30, 0.5);
padding: 20px;
border: solid 2px var(--color-modal-border);
border-radius: var(--border-radius-normal);
margin-top: 25px;
position: relative;
">
<h2>${title}</h2>
<br>
<p style="font-size: 1.25rem; padding: 0px">
${content}
</p>
<img src="https://forum-cfx-re.akamaized.net/original/5X/c/3/8/e/c38e8346a39c6483385c0727bee5c2abc705156a.png" style="
position: absolute;
right: 15px;
bottom: 15px;
opacity: 25%;
">
</div>`.replaceAll(/[\r\n]/g,"")};var prepCustomMessage=msg=>{if(!msg)return"";return"<br>"+msg.trim().replaceAll(/\n/g,"<br>")};async function PlayerCheckJoin(ctx){const sendTypedResp2=data=>ctx.send(data);if(!txConfig.banlist.enabled&&txConfig.whitelist.mode==="disabled"){return sendTypedResp2({allow:true})}if(anyUndefined(ctx.request.body,ctx.request.body.playerName,ctx.request.body.playerIds,ctx.request.body.playerHwids)){return sendTypedResp2({error:"Invalid request."})}const{playerName,playerIds,playerHwids}=ctx.request.body;if(typeof playerName!=="string")return sendTypedResp2({error:"playerName should be an string."});if(!Array.isArray(playerIds))return sendTypedResp2({error:"playerIds should be an array."});const{validIdsArray,validIdsObject}=parsePlayerIds(playerIds);if(validIdsArray.length<1)return sendTypedResp2({error:"Identifiers array must contain at least 1 valid identifier."});if(!Array.isArray(playerHwids))return sendTypedResp2({error:"playerHwids should be an array."});const{validHwidsArray}=filterPlayerHwids(playerHwids);try{if(txConfig.banlist.enabled){const checkTime=new TimeCounter;const result2=checkBan(validIdsArray,validIdsObject,validHwidsArray);txCore.metrics.txRuntime.banCheckTime.count(checkTime.stop().milliseconds);if(!result2.allow)return sendTypedResp2(result2)}if(txConfig.whitelist.mode==="adminOnly"){const checkTime=new TimeCounter;const result2=await checkAdminOnlyMode(validIdsArray,validIdsObject,playerName);txCore.metrics.txRuntime.whitelistCheckTime.count(checkTime.stop().milliseconds);if(!result2.allow)return sendTypedResp2(result2)}else if(txConfig.whitelist.mode==="approvedLicense"){const checkTime=new TimeCounter;const result2=await checkApprovedLicense(validIdsArray,validIdsObject,validHwidsArray,playerName);txCore.metrics.txRuntime.whitelistCheckTime.count(checkTime.stop().milliseconds);if(!result2.allow)return sendTypedResp2(result2)}else if(txConfig.whitelist.mode==="discordMember"){const checkTime=new TimeCounter;const result2=await checkDiscordMember(validIdsArray,validIdsObject,playerName);txCore.metrics.txRuntime.whitelistCheckTime.count(checkTime.stop().milliseconds);if(!result2.allow)return sendTypedResp2(result2)}else if(txConfig.whitelist.mode==="discordRoles"){const checkTime=new TimeCounter;const result2=await checkDiscordRoles(validIdsArray,validIdsObject,playerName);txCore.metrics.txRuntime.whitelistCheckTime.count(checkTime.stop().milliseconds);if(!result2.allow)return sendTypedResp2(result2)}return sendTypedResp2({allow:true})}catch(error){const msg=`Failed to check ban/whitelist status: ${error.message}`;console95.error(msg);console95.verbose.dir(error);return sendTypedResp2({error:msg})}}function checkBan(validIdsArray,validIdsObject,validHwidsArray){const ts=now();const filter2=action=>{return action.type==="ban"&&(!action.expiration||action.expiration>ts)&&!action.revocation.timestamp};const activeBans=txCore.database.actions.findMany(validIdsArray,validHwidsArray,filter2);if(activeBans.length){const ban=activeBans[0];const textKeys={title_permanent:txCore.translator.t("ban_messages.reject.title_permanent"),title_temporary:txCore.translator.t("ban_messages.reject.title_temporary"),label_expiration:txCore.translator.t("ban_messages.reject.label_expiration"),label_date:txCore.translator.t("ban_messages.reject.label_date"),label_author:txCore.translator.t("ban_messages.reject.label_author"),label_reason:txCore.translator.t("ban_messages.reject.label_reason"),label_id:txCore.translator.t("ban_messages.reject.label_id"),note_multiple_bans:txCore.translator.t("ban_messages.reject.note_multiple_bans"),note_diff_license:txCore.translator.t("ban_messages.reject.note_diff_license")};let title;let expLine="";if(ban.expiration){const duration=txCore.translator.tDuration((ban.expiration-ts)*1e3,{largest:2,units:["d","h","m"]});expLine=`<strong>${textKeys.label_expiration}:</strong> ${duration} <br>`;title=textKeys.title_temporary}else{title=textKeys.title_permanent}const banDate=new Date(ban.timestamp*1e3).toLocaleString(txCore.translator.canonical,{dateStyle:"medi
<strong>${textKeys.label_date}:</strong> ${banDate} <br>
<strong>${textKeys.label_reason}:</strong> ${xss(ban.reason)} <br>
<strong>${textKeys.label_id}:</strong> <codeid>${ban.id}</codeid> <br>
${authorLine}
${prepCustomMessage(txConfig.banlist.rejectionMessage)}
<span style="font-style: italic;">${note}</span>`);const matchingIds=ban.ids.filter(id=>validIdsArray.includes(id));const matchingHwids="hwids"in ban&&ban.hwids?ban.hwids.filter(hw=>validHwidsArray.includes(hw)):[];const combined=[...matchingIds,...matchingHwids];const summarizedIds=summarizeIdsArray(combined);const loggerReason=`active ban (${ban.id}) for identifiers ${summarizedIds}`;txCore.logger.server.write([{src:"tx",type:"playerJoinDenied",ts,data:{reason:loggerReason}}]);return{allow:false,reason}}else{return{allow:true}}}async function checkAdminOnlyMode(validIdsArray,validIdsObject,playerName){const textKeys={mode_title:txCore.translator.t("whitelist_messages.admin_only.mode_title"),insufficient_ids:txCore.translator.t("whitelist_messages.admin_only.insufficient_ids"),deny_message:txCore.translator.t("whitelist_messages.admin_only.deny_message")};if(!validIdsObject.license&&!validIdsObject.discord){return{allow:false,reason:rejectMessageTemplate(textKeys.mode_title,textKeys.insufficient_ids)}}const admin=txCore.adminStore.getAdminByIdentifiers(validIdsArray);if(admin)return{allow:true};const reason=rejectMessageTemplate(textKeys.mode_title,`${textKeys.deny_message} <br>
${prepCustomMessage(txConfig.whitelist.rejectionMessage)}`);return{allow:false,reason}}async function checkDiscordMember(validIdsArray,validIdsObject,playerName){const guildname=`<guildname>${txCore.discordBot.guildName}</guildname>`;const textKeys={mode_title:txCore.translator.t("whitelist_messages.guild_member.mode_title"),insufficient_ids:txCore.translator.t("whitelist_messages.guild_member.insufficient_ids"),deny_title:txCore.translator.t("whitelist_messages.guild_member.deny_title"),deny_message:txCore.translator.t("whitelist_messages.guild_member.deny_message",{guildname})};if(!validIdsObject.discord){return{allow:false,reason:rejectMessageTemplate(textKeys.mode_title,textKeys.insufficient_ids)}}let errorTitle,errorMessage;try{const{isMember,memberRoles}=await txCore.discordBot.resolveMemberRoles(validIdsObject.discord);if(isMember){return{allow:true}}else{errorTitle=textKeys.deny_title;errorMessage=textKeys.deny_message}}catch(error){errorTitle=`Error validating Discord Server Member Whitelist:`;errorMessage=`<code>${error.message}</code>`}const reason=rejectMessageTemplate(errorTitle,`${errorMessage} <br>
${prepCustomMessage(txConfig.whitelist.rejectionMessage)}`);return{allow:false,reason}}async function checkDiscordRoles(validIdsArray,validIdsObject,playerName){const guildname=`<guildname>${txCore.discordBot.guildName}</guildname>`;const textKeys={mode_title:txCore.translator.t("whitelist_messages.guild_roles.mode_title"),insufficient_ids:txCore.translator.t("whitelist_messages.guild_roles.insufficient_ids"),deny_notmember_title:txCore.translator.t("whitelist_messages.guild_roles.deny_notmember_title"),deny_notmember_message:txCore.translator.t("whitelist_messages.guild_roles.deny_notmember_message",{guildname}),deny_noroles_title:txCore.translator.t("whitelist_messages.guild_roles.deny_noroles_title"),deny_noroles_message:txCore.translator.t("whitelist_messages.guild_roles.deny_noroles_message",{guildname})};if(!validIdsObject.discord){return{allow:false,reason:rejectMessageTemplate(textKeys.mode_title,textKeys.insufficient_ids)}}let errorTitle,errorMessage;try{const{isMember,memberRoles}=await txCore.discordBot.resolveMemberRoles(validIdsObject.discord);if(isMember){const matchingRole=txConfig.whitelist.discordRoles.find(requiredRole=>memberRoles==null?void 0:memberRoles.includes(requiredRole));if(matchingRole){return{allow:true}}else{errorTitle=textKeys.deny_noroles_title;errorMessage=textKeys.deny_noroles_message}}else{errorTitle=textKeys.deny_notmember_title;errorMessage=textKeys.deny_notmember_message}}catch(error){errorTitle=`Error validating Discord Role Whitelist:`;errorMessage=`<code>${error.message}</code>`}const reason=rejectMessageTemplate(errorTitle,`${errorMessage} <br>
${prepCustomMessage(txConfig.whitelist.rejectionMessage)}`);return{allow:false,reason}}async function checkApprovedLicense(validIdsArray,validIdsObject,validHwidsArray,playerName){const textKeys={mode_title:txCore.translator.t("whitelist_messages.approved_license.mode_title"),insufficient_ids:txCore.translator.t("whitelist_messages.approved_license.insufficient_ids"),deny_title:txCore.translator.t("whitelist_messages.approved_license.deny_title"),request_id_label:txCore.translator.t("whitelist_messages.approved_license.request_id_label")};if(!validIdsObject.license){return{allow:false,reason:rejectMessageTemplate(textKeys.mode_title,textKeys.insufficient_ids)}}let player;try{player=playerResolver_default(null,null,validIdsObject.license);const dbData=player.getDbData();if(dbData&&dbData.tsWhitelisted){return{allow:true}}}catch(error){}const{displayName,pureName}=cleanPlayerName_default(playerName);const ts=now();const allIdsFilter=x=>{return validIdsArray.includes(x.identifier)};const approvals=txCore.database.whitelist.findManyApprovals(allIdsFilter);if(approvals.length){if(typeof player!=="undefined"&&player.license){player.setWhitelist(true)}else{txCore.database.players.register({license:validIdsObject.license,ids:validIdsArray,hwids:validHwidsArray,displayName,pureName,playTime:0,tsLastConnection:ts,tsJoined:ts,tsWhitelisted:ts})}txCore.database.whitelist.removeManyApprovals(allIdsFilter);txCore.database.whitelist.removeManyRequests({license:validIdsObject.license});return{allow:true}}let discordTag,discordAvatar;if(validIdsObject.discord&&txCore.discordBot.isClientReady){try{const{tag,avatar}=await txCore.discordBot.resolveMemberProfile(validIdsObject.discord);discordTag=tag;discordAvatar=avatar}catch(error){}}let wlRequestId;const requests=txCore.database.whitelist.findManyRequests({license:validIdsObject.license});if(requests.length){wlRequestId=requests[0].id;txCore.database.whitelist.updateRequest(validIdsObject.license,{playerDisplayName:displayName,playerPureName:pureName,discordTag,discordAvatar,tsLastAttempt:ts})}else{wlRequestId=txCore.database.whitelist.registerRequest({license:validIdsObject.license,playerDisplayName:displayName,playerPureName:pureName,discordTag,discordAvatar,tsLastAttempt:ts});txCore.fxRunner.sendEvent("whitelistRequest",{action:"requested",playerName:displayName,requestId:wlRequestId,license:validIdsObject.license})}const reason=rejectMessageTemplate(textKeys.deny_title,`<strong>${textKeys.request_id_label}:</strong>
<codeid>${wlRequestId}</codeid> <br>
${prepCustomMessage(txConfig.whitelist.rejectionMessage)}`);return{allow:false,reason}}var modulename85="WebServer:WhitelistPage";var console96=console_default(modulename85);async function WhitelistPage(ctx){const respData={headerTitle:"Whitelist",hasWhitelistPermission:ctx.admin.hasPermission("players.whitelist"),currentWhitelistMode:txConfig.whitelist.mode};return ctx.utils.render("main/whitelist",respData)}var modulename86="WebServer:WhitelistList";var console97=console_default(modulename86);async function WhitelistList(ctx){const table=ctx.params.table;if(table==="requests"){return await handleRequests(ctx)}else if(table==="approvals"){return await handleApprovals(ctx)}else{return ctx.send({error:"unknown table"})}}async function handleRequests(ctx){var _a13,_b2;const sendTypedResp2=data=>ctx.send(data);const requests=txCore.database.whitelist.findManyRequests().reverse();let filtered=requests;const searchString=(_a13=ctx.request.query)==null?void 0:_a13.searchString;if(typeof searchString==="string"&&searchString.length){const fuse=new Fuse(requests,{keys:["id","playerPureName","discordTag"],threshold:.3});const{pureName}=cleanPlayerName_default(searchString);filtered=fuse.search(pureName).map(x=>x.item)}const pageSize=15;const pageinput=(_b2=ctx.request.query)==null?void 0:_b2.page;let currPage=1;if(typeof pageinput==="string"){if(/^\d+$/.test(pageinput)){currPage=parseInt(pageinput);if(currPage<1){return sendTypedResp2({error:"page should be >= 1"})}}else{return sendTypedResp2({error:"page should be a number"})}}const skip=(currPage-1)*pageSize;const paginated=filtered.slice(skip,skip+pageSize);return sendTypedResp2({cntTotal:requests.length,cntFiltered:filtered.length,newest:requests.length?requests[0].tsLastAttempt:0,totalPages:Math.ceil(filtered.length/pageSize),currPage,requests:paginated})}async function handleApprovals(ctx){const sendTypedResp2=data=>ctx.send(data);const approvals=txCore.database.whitelist.findManyApprovals().reverse();return sendTypedResp2(approvals)}var modulename87="WebServer:WhitelistActions";var console98=console_default(modulename87);var anyUndefined2=(...args2)=>[...args2].some(x=>typeof x==="undefined");async function WhitelistActions(ctx){if(anyUndefined2(ctx.params.action)){return ctx.utils.error(400,"Invalid Request")}const{table,action}=ctx.params;const sendTypedResp2=data=>ctx.send(data);if(!ctx.admin.testPermission("players.whitelist",modulename87)){return sendTypedResp2({error:"You don't have permission to execute this action."})}if(table==="approvals"){return sendTypedResp2(await handleApprovals2(ctx,action))}else if(table==="requests"){return sendTypedResp2(await handleRequests2(ctx,action))}else{return sendTypedResp2({error:"unknown table"})}}async function handleApprovals2(ctx,action){var _a13;if(typeof((_a13=ctx.request.body)==null?void 0:_a13.identifier)!=="string"){return{error:"identifier not specified"}}const identifier=ctx.request.body.identifier;const{isIdValid,idType,idValue,idlowerCased}=parsePlayerId(identifier);if(!isIdValid||!idType||!idValue||!idlowerCased){return{error:"Error: the provided identifier does not seem to be valid"}}if(action==="add"){let playerAvatar=null;let playerName=idValue.length>8?`${idType}...${idValue.slice(-8)}`:`${idType}:${idValue}`;if(idType==="discord"){try{const{tag,avatar}=await txCore.discordBot.resolveMemberProfile(idValue);playerName=tag;playerAvatar=avatar}catch(error){}}try{txCore.database.whitelist.registerApproval({identifier:idlowerCased,playerName,playerAvatar,tsApproved:now(),approvedBy:ctx.admin.name});txCore.fxRunner.sendEvent("whitelistPreApproval",{action:"added",identifier:idlowerCased,playerName,adminName:ctx.admin.name})}catch(error){return{error:`Failed to save wl approval: ${error.message}`}}ctx.admin.logAction(`Added whitelist approval for ${playerName}.`);return{success:true}}else if(action==="remove"){try{txCore.database.whitelist.removeManyApprovals({identifier:idlowerCased});txCore.fxRunner.sendEvent("whitelistPreApproval",{action:"removed",identifier:idlowerCased,adminName:ctx.admin.name})}catch(er
body {
margin: 0;
}
.notice {
font-family: sans-serif;
font-size: 1.5em;
text-align: center;
background-color: #222326;
color: #F7F7F8;
padding: 2em;
border: 1px solid #333539;
border-radius: 0.5em;
}
.notice a {
color: #F00A53;
}
</style>
<p class="notice">
User logged out. <br>
Redirecting to <a href="/login#expired" target="_parent">login page</a>...
</p>
<script>
// Notify parent window that auth failed
window.parent.postMessage({ type: 'logoutNotice' });
// If parent redirect didn't work, redirect here
setTimeout(function() {
window.parent.location.href = '/login#expired';
}, 2000);
</script>`;var intercomAuthMw=async(ctx,next)=>{var _a13;if(typeof((_a13=ctx.request.body)==null?void 0:_a13.txAdminToken)!=="string"||ctx.request.body.txAdminToken!==txCore.webServer.luaComToken){return ctx.send({error:"invalid token"})}await next()};var webAuthMw=async(ctx,next)=>{const authResult=checkRequestAuth(ctx.request.headers,ctx.ip,ctx.txVars.isLocalRequest,ctx.sessTools);if(!authResult.success){ctx.sessTools.destroy();if(authResult.rejectReason){console104.verbose.warn(`Invalid session auth: ${authResult.rejectReason}`)}return ctx.send(webLogoutPage)}ctx.admin=authResult.admin;await next()};var apiAuthMw=async(ctx,next)=>{var _a13;const sendTypedResp2=data=>ctx.send(data);const authResult=checkRequestAuth(ctx.request.headers,ctx.ip,ctx.txVars.isLocalRequest,ctx.sessTools);if(!authResult.success){ctx.sessTools.destroy();if(authResult.rejectReason&&(authResult.rejectReason!=="nui_admin_not_found"||console104.isVerbose)){console104.verbose.warn(`Invalid session auth: ${authResult.rejectReason}`)}return sendTypedResp2({logout:true,reason:authResult.rejectReason??"no session"})}if(ctx.txVars.isWebInterface){const sessToken=(_a13=authResult.admin)==null?void 0:_a13.csrfToken;const headerToken=ctx.headers["x-txadmin-csrftoken"];if(!sessToken||!headerToken||sessToken!==headerToken){console104.verbose.warn(`Invalid CSRF token: ${ctx.path}`);const msg=headerToken?"Error: Invalid CSRF token, please refresh the page or try to login again.":"Error: Missing HTTP header 'x-txadmin-csrftoken'. This likely means your files are not updated or you are using some reverse proxy that is removing this header from the HTTP request.";return sendTypedResp2({type:"error",msg,error:msg})}}ctx.admin=authResult.admin;await next()};var router_default=()=>{const router=new import_router.default;const authLimiter=(0,import_koa_ratelimit.default)({driver:"memory",db:new Map,duration:txConfig.webServer.limiterMinutes*60*1e3,errorMessage:JSON.stringify({error:`Too many attempts. Blocked for ${txConfig.webServer.limiterMinutes} minutes.`,errorTitle:"Too many attempts.",errorMessage:`Blocked for ${txConfig.webServer.limiterMinutes} minutes.`}),max:txConfig.webServer.limiterAttempts,disableHeader:true,id:ctx=>ctx.txVars.realIP});router.get("/legacy/adminManager",webAuthMw,AdminManagerPage);router.get("/legacy/advanced",webAuthMw,AdvancedPage);router.get("/legacy/cfgEditor",webAuthMw,CFGEditorPage);router.get("/legacy/diagnostics",webAuthMw,Diagnostics);router.get("/legacy/masterActions",webAuthMw,MasterActionsPage);router.get("/legacy/resources",webAuthMw,Resources);router.get("/legacy/serverLog",webAuthMw,ServerLog);router.get("/legacy/whitelist",webAuthMw,WhitelistPage);router.get("/legacy/setup",webAuthMw,SetupGet);router.get("/legacy/deployer",webAuthMw,DeployerStepper);router.get("/auth/self",apiAuthMw,AuthSelf);router.post("/auth/password",authLimiter,AuthVerifyPassword);router.post("/auth/logout",authLimiter,AuthLogout);router.post("/auth/addMaster/pin",authLimiter,AuthAddMasterPin);router.post("/auth/addMaster/callback",authLimiter,AuthAddMasterCallback);router.post("/auth/addMaster/save",authLimiter,AuthAddMasterSave);router.get("/auth/cfxre/redirect",authLimiter,AuthProviderRedirect);router.post("/auth/cfxre/callback",authLimiter,AuthProviderCallback);router.post("/auth/changePassword",apiAuthMw,AuthChangePassword);router.get("/auth/getIdentifiers",apiAuthMw,AuthGetIdentifiers);router.post("/auth/changeIdentifiers",apiAuthMw,AuthChangeIdentifiers);router.post("/adminManager/getModal/:modalType",webAuthMw,AdminManagerGetModal);router.post("/adminManager/:action",apiAuthMw,AdminManagerActions);router.post("/setup/:action",apiAuthMw,SetupPost);router.get("/deployer/status",apiAuthMw,DeployerStatus);router.post("/deployer/recipe/:action",apiAuthMw,DeployerActions);router.get("/settings/configs",apiAuthMw,GetSettingsConfigs);router.post("/settings/configs/:card",apiAuthMw,SaveSettingsConfigs);router.get("/settings/banTemplates",apiAuthMw,GetBanTemplates);router.post("/settings/banTemplates",apiAuthMw,SaveBanTemplates);router.post("/settings/
import { injectIntoGlobalHook } from "${viteOrigin}/@react-refresh";
injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
</script>
<script type="module" src="${viteOrigin}/@vite/client"></script>
<script type="module" src="${viteOrigin}/src/main.tsx"></script>`;var tmpDefaultTheme="dark";var tmpDefaultThemes=["dark","light"];var tmpCustomThemes=[];async function getReactIndex(ctx){if(txDevEnv.ENABLED||!htmlFile){try{const indexPath=txDevEnv.ENABLED?import_node_path18.default.join(txDevEnv.SRC_PATH,"/panel/index.html"):import_node_path18.default.join(txEnv.txAdminResourcePath,"panel/index.html");const rawHtmlFile=await import_promises19.default.readFile(indexPath,"utf-8");if(txDevEnv.ENABLED){htmlFile=rawHtmlFile.replaceAll(/.+data-prod-only.+\r?\n/gm,"")}else{htmlFile=rawHtmlFile.replaceAll(/.+data-dev-only.+\r?\n/gm,"")}}catch(error){if(error.code=="ENOENT"){return`<h1> index.html not found:</h1><pre>You probably deleted the 'citizen/system_resources/monitor/panel/index.html' file, or the folders above it.</pre>`}else{return`<h1> index.html load error:</h1><pre>${error.message}</pre>`}}}const authResult=checkRequestAuth(ctx.request.headers,ctx.ip,ctx.txVars.isLocalRequest,ctx.sessTools);let authedAdmin=false;if(authResult.success){authedAdmin=authResult.admin}const basePath2=ctx.txVars.isWebInterface?"/":consts_default.nuiWebpipePath;const serverName2=txConfig.general.serverName||txEnv.profile;const injectedConsts={fxsVersion:txEnv.fxsVersionDisplay,fxsOutdated:txCore.updateChecker.fxsUpdateData,txaVersion:txEnv.txaVersion,txaOutdated:txCore.updateChecker.txaUpdateData,serverTimezone,isWindows:txEnv.isWindows,isZapHosting:convars.isZapHosting,isPterodactyl:convars.isPterodactyl,isWebInterface:ctx.txVars.isWebInterface,showAdvanced:txDevEnv.ENABLED||console107.isVerbose,hasMasterAccount:txCore.adminStore.hasAdmins(true),defaultTheme:tmpDefaultTheme,customThemes:tmpCustomThemes.map(({name,isDark})=>({name,isDark})),adsData:convars.adsData,providerLogo:convars.providerLogo,providerName:convars.providerName,preAuth:authedAdmin&&authedAdmin.getAuthData()};const replacers={};replacers.basePath=`<base href="${basePath2}">`;replacers.ogTitle=`txAdmin - ${serverName2}`;replacers.ogDescripttion=`Manage & Monitor your FiveM/RedM Server with txAdmin v${txEnv.txaVersion} atop FXServer ${txEnv.fxsVersion}`;replacers.txConstsInjection=`<script>window.txConsts = ${JSON.stringify(injectedConsts)};</script>`;replacers.devModules=txDevEnv.ENABLED?devModulesScript:"";if(tmpCustomThemes.length){const cssThemes=[];for(const theme of tmpCustomThemes){const cssVars=[];for(const[name,value]of Object.entries(theme.style)){cssVars.push(`--${name}: ${value};`)}cssThemes.push(`.theme-${theme.name} { ${cssVars.join(" ")} }`)}replacers.customThemesStyle=`<style>${cssThemes.join("\n")}</style>`}else{replacers.customThemesStyle=""}const themeCookie=ctx.cookies.get("txAdmin-theme");if(themeCookie){if(tmpDefaultThemes.includes(themeCookie)){replacers.htmlClasses=themeCookie}else{const selectedCustomTheme=tmpCustomThemes.find(theme=>theme.name===themeCookie);if(!selectedCustomTheme){replacers.htmlClasses=tmpDefaultTheme}else{const lightDarkSelector=selectedCustomTheme.isDark?"dark":"light";replacers.htmlClasses=`${lightDarkSelector} theme-${selectedCustomTheme.name}`}}}else{replacers.htmlClasses=tmpDefaultTheme}let htmlOut=htmlFile;for(const[placeholder,value]of Object.entries(replacers)){const replacerRegex=new RegExp(`(<!--\\s*)?{{${placeholder}}}(\\s*-->)?`,"g");htmlOut=htmlOut.replaceAll(replacerRegex,value)}if(!txDevEnv.ENABLED){const base=ctx.txVars.isWebInterface?`./`:`nui://monitor/panel/`;htmlOut=htmlOut.replace(/src="\.\/index-(\w+)\.js"/,`src="${base}index-$1.js"`);htmlOut=htmlOut.replace(/href="\.\/index-(\w+)\.css"/,`href="${base}index-$1.css"`)}return htmlOut}var modulename97="WebCtxUtils";var console108=console_default(modulename97);var xss2=xss_default();var getRenderErrorText=(view,error,data)=>{var _a13;console108.error(`Error rendering ${view}.`);console108.verbose.dir(error);if((_a13=data==null?void 0:data.discord)==null?void 0:_a13.token)data.discord.token="[redacted]";return['<pre style="color: red">',`Error rendering '${view}'.`,`Message: ${xss2(error.message)}`,"The data provided was:","================",xss2(JSO
body {
margin: 0;
}
.notice {
font-family: sans-serif;
font-size: 1.5em;
text-align: center;
background-color: #222326;
color: #F7F7F8;
padding: 2em;
border: 1px solid #333539;
border-radius: 0.5em;
}
.notice a {
color: #F00A53;
}
</style>
<p class="notice">
Redirecting to <a href="{{href}}" target="_parent">{{href}}</a>...
</p>
<script>
// Notify parent window that auth failed
window.parent.postMessage({ type: 'navigateToPage', href: '{{href}}'});
// If parent redirect didn't work, redirect here
setTimeout(function() {
window.parent.location.href = '{{href}}';
}, 2000);
</script>`;async function loadWebTemplate(name){if(txDevEnv.ENABLED||!templateCache.has(name)){try{const rawTemplate=await import_promises20.default.readFile(getWebViewPath(name),"utf-8");const compiled=import_ejs.default.compile(rawTemplate,getEjsOptions(name+".ejs"));templateCache.set(name,compiled)}catch(error){if(error.code=="ENOENT"){throw new Error([`The '${name}' template was not found:`,`You probably deleted the 'citizen/system_resources/monitor/web/${name}.ejs' file, or the folders above it.`].join("\n"))}else{throw error}}}return templateCache.get(name)}async function renderView(view,possiblyAuthedAdmin,data,txVars){data.adminUsername=(possiblyAuthedAdmin==null?void 0:possiblyAuthedAdmin.name)??"unknown user";data.adminIsMaster=possiblyAuthedAdmin&&possiblyAuthedAdmin.isMaster;data.profilePicture=(possiblyAuthedAdmin==null?void 0:possiblyAuthedAdmin.profilePicture)??"img/default_avatar.png";data.isTempPassword=possiblyAuthedAdmin&&possiblyAuthedAdmin.isTempPassword;data.isLinux=!txEnv.isWindows;data.showAdvanced=txDevEnv.ENABLED||console108.isVerbose;try{return await loadWebTemplate(view).then(template2=>template2(data))}catch(error){return getRenderErrorText(view,error,data)}}async function ctxUtilsMw(ctx,next){const isWebInterface=ctx.txVars.isWebInterface;const renderUtil=async(view,data)=>{const possiblyAuthedAdmin=ctx.admin;let legacyTheme="";const themeCookie=ctx.cookies.get("txAdmin-theme");if(!themeCookie||themeCookie==="dark"||!isWebInterface){legacyTheme="theme--dark"}else{const selectorTheme=tmpCustomThemes.find(theme=>theme.name===themeCookie);if(selectorTheme==null?void 0:selectorTheme.isDark){legacyTheme="theme--dark"}}const baseViewData={isWebInterface,basePath:isWebInterface?"/":consts_default.nuiWebpipePath,resourcePath:isWebInterface?"":RESOURCE_PATH,serverProfile:txEnv.profile,serverName:txConfig.general.serverName||txEnv.profile,uiTheme:legacyTheme,fxServerVersion:txEnv.fxsVersionDisplay,txAdminVersion:txEnv.txaVersion,providerName:convars.providerName,jsInjection:getJavascriptConsts({isZapHosting:convars.isZapHosting,isPterodactyl:convars.isPterodactyl,isWebInterface,csrfToken:(possiblyAuthedAdmin==null?void 0:possiblyAuthedAdmin.csrfToken)??"not_set",TX_BASE_PATH:isWebInterface?"":consts_default.nuiWebpipePath,PAGE_TITLE:(data==null?void 0:data.headerTitle)??"txAdmin"})};const renderData=Object.assign(baseViewData,data);ctx.body=await renderView(view,possiblyAuthedAdmin,renderData,ctx.txVars);ctx.type="text/html"};const errorUtil2=(httpStatus=500,message3="unknown error")=>{ctx.status=httpStatus;ctx.body={status:"error",code:httpStatus,message:message3}};const legacyNavigateToPage=href=>{ctx.body=legacyNavigateHtmlTemplate.replace(/{{href}}/g,href);ctx.type="text/html"};const serveReactIndex=async()=>{ctx.body=await getReactIndex(ctx);ctx.type="text/html"};ctx.utils={render:renderUtil,error:errorUtil2,serveReactIndex,legacyNavigateToPage};ctx.send=data=>{ctx.body=data};return next()}var import_mnemonist=__toESM(require_mnemonist(),1);var import_node_crypto6=require("node:crypto");var import_cookie=__toESM(require_cookie(),1);var SessionMemoryStorage=class{constructor(maxAgeMs){this.sessions=new import_mnemonist.LRUCacheWithDelete(5e3);this.maxAgeMs=24*60*60*1e3;if(maxAgeMs){this.maxAgeMs=maxAgeMs}setInterval(()=>{const now3=Date.now();for(const[key,sess]of this.sessions){if(sess.expires<now3){this.sessions.delete(key)}}},5*6e4)}get(key){const stored=this.sessions.get(key);if(!stored)return;if(stored.expires<Date.now()){this.sessions.delete(key);return}return stored.data}set(key,sess){this.sessions.set(key,{expires:Date.now()+this.maxAgeMs,data:sess})}refresh(key){const stored=this.sessions.get(key);if(!stored)return;this.sessions.set(key,{expires:Date.now()+this.maxAgeMs,data:stored.data})}destroy(key){return this.sessions.delete(key)}get size(){return this.sessions.size}};var isValidSessId=sessId=>{if(typeof sessId!=="string")return false;if(sessId.length!==36)return false;return true};var koaSessMw=(cookieName,store)=>{const cookieOptions={path:"/",maxAge:store.maxAgeMs,httpOnly:true,sa