Initial release for SPT 3.9

This commit is contained in:
2024-07-20 18:08:38 +02:00
parent 7df25ba694
commit c83da69a3e
713 changed files with 34110 additions and 1 deletions

25
types/utils/App.d.ts vendored Normal file
View File

@@ -0,0 +1,25 @@
import { OnLoad } from "@spt/di/OnLoad";
import { OnUpdate } from "@spt/di/OnUpdate";
import { ICoreConfig } from "@spt/models/spt/config/ICoreConfig";
import { ILogger } from "@spt/models/spt/utils/ILogger";
import { ConfigServer } from "@spt/servers/ConfigServer";
import { HttpServer } from "@spt/servers/HttpServer";
import { LocalisationService } from "@spt/services/LocalisationService";
import { EncodingUtil } from "@spt/utils/EncodingUtil";
import { TimeUtil } from "@spt/utils/TimeUtil";
export declare class App {
protected logger: ILogger;
protected timeUtil: TimeUtil;
protected localisationService: LocalisationService;
protected configServer: ConfigServer;
protected encodingUtil: EncodingUtil;
protected httpServer: HttpServer;
protected onLoadComponents: OnLoad[];
protected onUpdateComponents: OnUpdate[];
protected onUpdateLastRun: {};
protected coreConfig: ICoreConfig;
constructor(logger: ILogger, timeUtil: TimeUtil, localisationService: LocalisationService, configServer: ConfigServer, encodingUtil: EncodingUtil, httpServer: HttpServer, onLoadComponents: OnLoad[], onUpdateComponents: OnUpdate[]);
load(): Promise<void>;
protected update(onUpdateComponents: OnUpdate[]): Promise<void>;
protected logUpdateException(err: any, updateable: OnUpdate): void;
}

7
types/utils/AsyncQueue.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
import { IAsyncQueue } from "@spt/models/spt/utils/IAsyncQueue";
import { ICommand } from "@spt/models/spt/utils/ICommand";
export declare class AsyncQueue implements IAsyncQueue {
protected commandsQueue: ICommand[];
constructor();
waitFor(command: ICommand): Promise<any>;
}

11
types/utils/CompareUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,11 @@
export declare class CompareUtil {
private static typesToCheckAgainst;
/**
* This function does an object comparison, equivalent to applying reflections
* and scanning for all possible properties including arrays.
* @param v1 value 1 to compare
* @param v2 value 2 to compare
* @returns true if equal, false if not
*/
recursiveCompare(v1: any, v2: any): boolean;
}

54
types/utils/DatabaseImporter.d.ts vendored Normal file
View File

@@ -0,0 +1,54 @@
import { OnLoad } from "@spt/di/OnLoad";
import { IHttpConfig } from "@spt/models/spt/config/IHttpConfig";
import { ILogger } from "@spt/models/spt/utils/ILogger";
import { ImageRouter } from "@spt/routers/ImageRouter";
import { ConfigServer } from "@spt/servers/ConfigServer";
import { DatabaseServer } from "@spt/servers/DatabaseServer";
import { LocalisationService } from "@spt/services/LocalisationService";
import { EncodingUtil } from "@spt/utils/EncodingUtil";
import { HashUtil } from "@spt/utils/HashUtil";
import { ImporterUtil } from "@spt/utils/ImporterUtil";
import { JsonUtil } from "@spt/utils/JsonUtil";
import { VFS } from "@spt/utils/VFS";
export declare class DatabaseImporter implements OnLoad {
protected logger: ILogger;
protected vfs: VFS;
protected jsonUtil: JsonUtil;
protected localisationService: LocalisationService;
protected databaseServer: DatabaseServer;
protected imageRouter: ImageRouter;
protected encodingUtil: EncodingUtil;
protected hashUtil: HashUtil;
protected importerUtil: ImporterUtil;
protected configServer: ConfigServer;
private hashedFile;
private valid;
private filepath;
protected httpConfig: IHttpConfig;
constructor(logger: ILogger, vfs: VFS, jsonUtil: JsonUtil, localisationService: LocalisationService, databaseServer: DatabaseServer, imageRouter: ImageRouter, encodingUtil: EncodingUtil, hashUtil: HashUtil, importerUtil: ImporterUtil, configServer: ConfigServer);
/**
* Get path to spt data
* @returns path to data
*/
getSptDataPath(): string;
onLoad(): Promise<void>;
/**
* Read all json files in database folder and map into a json object
* @param filepath path to database folder
*/
protected hydrateDatabase(filepath: string): Promise<void>;
protected onReadValidate(fileWithPath: string, data: string): void;
getRoute(): string;
protected validateFile(filePathAndName: string, fileData: any): boolean;
/**
* Find and map files with image router inside a designated path
* @param filepath Path to find files in
*/
loadImages(filepath: string, directories: string[], routes: string[]): void;
/**
* Check for a path override in the http json config file
* @param imagePath Key
* @returns override for key
*/
protected getImagePathOverride(imagePath: string): string;
}

15
types/utils/EncodingUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,15 @@
export declare class EncodingUtil {
encode(value: string, encode: EncodeType): string;
decode(value: string, encode: EncodeType): string;
fromBase64(value: string): string;
toBase64(value: string): string;
fromHex(value: string): string;
toHex(value: string): string;
}
export declare enum EncodeType {
BASE64 = "base64",
HEX = "hex",
ASCII = "ascii",
BINARY = "binary",
UTF8 = "utf8"
}

25
types/utils/HashUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,25 @@
/// <reference types="node" />
/// <reference types="node" />
import crypto from "node:crypto";
import fs from "node:fs";
import { TimeUtil } from "@spt/utils/TimeUtil";
export declare class HashUtil {
protected timeUtil: TimeUtil;
constructor(timeUtil: TimeUtil);
/**
* Create a 24 character id using the sha256 algorithm + current timestamp
* @returns 24 character hash
*/
generate(): string;
generateMd5ForData(data: string): string;
generateSha1ForData(data: string): string;
generateCRC32ForFile(filePath: fs.PathLike): number;
/**
* Create a hash for the data parameter
* @param algorithm algorithm to use to hash
* @param data data to be hashed
* @returns hash value
*/
generateHashForData(algorithm: string, data: crypto.BinaryLike): string;
generateAccountId(): number;
}

8
types/utils/HttpFileUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
/// <reference types="node" />
import { ServerResponse } from "node:http";
import { HttpServerHelper } from "@spt/helpers/HttpServerHelper";
export declare class HttpFileUtil {
protected httpServerHelper: HttpServerHelper;
constructor(httpServerHelper: HttpServerHelper);
sendFile(resp: ServerResponse, filePath: string): void;
}

38
types/utils/HttpResponseUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,38 @@
import { IGetBodyResponseData } from "@spt/models/eft/httpResponse/IGetBodyResponseData";
import { INullResponseData } from "@spt/models/eft/httpResponse/INullResponseData";
import { IItemEventRouterResponse } from "@spt/models/eft/itemEvent/IItemEventRouterResponse";
import { BackendErrorCodes } from "@spt/models/enums/BackendErrorCodes";
import { LocalisationService } from "@spt/services/LocalisationService";
import { JsonUtil } from "@spt/utils/JsonUtil";
export declare class HttpResponseUtil {
protected jsonUtil: JsonUtil;
protected localisationService: LocalisationService;
constructor(jsonUtil: JsonUtil, localisationService: LocalisationService);
protected clearString(s: string): any;
/**
* Return passed in data as JSON string
* @param data
* @returns
*/
noBody(data: any): any;
/**
* Game client needs server responses in a particular format
* @param data
* @param err
* @param errmsg
* @returns
*/
getBody<T>(data: T, err?: number, errmsg?: string, sanitize?: boolean): IGetBodyResponseData<T>;
getUnclearedBody(data: any, err?: number, errmsg?: string): string;
emptyResponse(): IGetBodyResponseData<string>;
nullResponse(): INullResponseData;
emptyArrayResponse(): IGetBodyResponseData<any[]>;
/**
* Add an error into the 'warnings' array of the client response message
* @param output IItemEventRouterResponse
* @param message Error message
* @param errorCode Error code
* @returns IItemEventRouterResponse
*/
appendErrorToOutput(output: IItemEventRouterResponse, message?: string, errorCode?: BackendErrorCodes): IItemEventRouterResponse;
}

21
types/utils/ImporterUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,21 @@
import { JsonUtil } from "@spt/utils/JsonUtil";
import { VFS } from "@spt/utils/VFS";
export declare class ImporterUtil {
protected vfs: VFS;
protected jsonUtil: JsonUtil;
constructor(vfs: VFS, jsonUtil: JsonUtil);
/**
* Load files into js objects recursively (asynchronous)
* @param filepath Path to folder with files
* @returns Promise<T> return T type associated with this class
*/
loadRecursiveAsync<T>(filepath: string, onReadCallback?: (fileWithPath: string, data: string) => void, onObjectDeserialized?: (fileWithPath: string, object: any) => void): Promise<T>;
/**
* Load files into js objects recursively (synchronous)
* @param filepath Path to folder with files
* @returns
*/
loadRecursive<T>(filepath: string, onReadCallback?: (fileWithPath: string, data: string) => void, onObjectDeserialized?: (fileWithPath: string, object: any) => void): T;
loadAsync<T>(filepath: string, strippablePath?: string, onReadCallback?: (fileWithPath: string, data: string) => void, onObjectDeserialized?: (fileWithPath: string, object: any) => void): Promise<T>;
protected placeObject<T>(fileDeserialized: any, strippedFilePath: string, result: T, strippablePath: string): void;
}

79
types/utils/JsonUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,79 @@
import { IParseOptions, IStringifyOptions, Reviver } from "jsonc/lib/interfaces";
import { ILogger } from "@spt/models/spt/utils/ILogger";
import { HashUtil } from "@spt/utils/HashUtil";
import { VFS } from "@spt/utils/VFS";
export declare class JsonUtil {
protected vfs: VFS;
protected hashUtil: HashUtil;
protected logger: ILogger;
protected fileHashes?: Map<string, string>;
protected jsonCacheExists: boolean;
protected jsonCachePath: string;
constructor(vfs: VFS, hashUtil: HashUtil, logger: ILogger);
/**
* From object to string
* @param data object to turn into JSON
* @param prettify Should output be prettified
* @returns string
*/
serialize(data: any, prettify?: boolean): string;
/**
* From object to string
* @param data object to turn into JSON
* @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
* @returns string
*/
serializeAdvanced(data: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
/**
* From object to string
* @param data object to turn into JSON
* @param filename Name of file being serialized
* @param options Stringify options or a replacer.
* @returns The string converted from the JavaScript value
*/
serializeJsonC(data: any, filename?: string | undefined, options?: IStringifyOptions | Reviver): string | undefined;
serializeJson5(data: any, filename?: string | undefined, prettify?: boolean): string | undefined;
/**
* From string to object
* @param jsonString json string to turn into object
* @param filename Name of file being deserialized
* @returns object
*/
deserialize<T>(jsonString: string, filename?: string): T | undefined;
/**
* From string to object
* @param jsonString json string to turn into object
* @param filename Name of file being deserialized
* @param options Parsing options
* @returns object
*/
deserializeJsonC<T>(jsonString: string, filename?: string, options?: IParseOptions): T | undefined;
deserializeJson5<T>(jsonString: string, filename?: string): T | undefined;
deserializeWithCacheCheckAsync<T>(jsonString: string, filePath: string): Promise<T | undefined>;
/**
* Take json from file and convert into object
* Perform valadation on json during process if json file has not been processed before
* @param jsonString String to turn into object
* @param filePath Path to json file being processed
* @returns Object
*/
deserializeWithCacheCheck<T>(jsonString: string, filePath: string): T | undefined;
/**
* Create file if nothing found
* @param jsonCachePath path to cache
*/
protected ensureJsonCacheExists(jsonCachePath: string): void;
/**
* Read contents of json cache and add to class field
* @param jsonCachePath Path to cache
*/
protected hydrateJsonCache(jsonCachePath: string): void;
/**
* Convert into string and back into object to clone object
* @param objectToClone Item to clone
* @returns Cloned parameter
* @deprecated Use ICloner implementations, such as RecursiveCloner or StructuredCloner
*/
clone<T>(objectToClone: T): T;
}

53
types/utils/MathUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,53 @@
export declare class MathUtil {
/**
* Helper to create the sum of all array elements
* @param {array} values The array with numbers of which to calculate the sum
* @return {number} sum(values)
*/
arraySum(values: number[]): number;
/**
* Helper to create the cumulative sum of all array elements
* arrayCumsum([1, 2, 3, 4]) = [1, 3, 6, 10]
* @param {array} values The array with numbers of which to calculate the cumulative sum
* @return {array} cumsum(values)
*/
arrayCumsum(values: number[]): number[];
/**
* Helper to create the product of each element times factor
* @param {array} values The array of numbers which shall be multiplied by the factor
* @return {array} array times factor
*/
arrayProd(values: number[], factor: number): number[];
/**
* Helper to add a constant to all array elements
* @param {array} values The array of numbers to which the summand should be added
* @return {array} array plus summand
*/
arrayAdd(values: number[], summand: number): number[];
/**
* Map a value from an input range to an output range linearly
*
* Example:
* a_min = 0; a_max=1;
* b_min = 1; b_max=3;
* MathUtil.mapToRange(0.5, a_min, a_max, b_min, b_max) // returns 2
*
* @param {number} x The value from input range to be mapped to output range
* @param {number} minIn min of input range
* @param {number} maxIn max of input range
* @param {number} minOut min of output range
* @param {number} maxOut max of outout range
* @return {number} the result of the mapping
*/
mapToRange(x: number, minIn: number, maxIn: number, minOut: number, maxOut: number): number;
/**
* Linear interpolation
* e.g. used to do a continuous integration for quest rewards which are defined for specific support centers of pmcLevel
*
* @param {string} xp the point of x at which to interpolate
* @param {array} x support points in x (of same length as y)
* @param {array} y support points in y (of same length as x)
* @return {number} y(xp)
*/
interp1(xp: number, x: number[], y: number[]): number | undefined;
}

14
types/utils/ObjectId.d.ts vendored Normal file
View File

@@ -0,0 +1,14 @@
/// <reference types="node" />
import { TimeUtil } from "@spt/utils/TimeUtil";
export declare class ObjectId {
protected timeUtil: TimeUtil;
constructor(timeUtil: TimeUtil);
protected randomBytes: Buffer;
protected constglobalCounter: number;
protected consttime: number;
protected globalCounter: number;
protected time: number;
incGlobalCounter(): number;
toHexString(byteArray: string | any[] | Buffer): string;
generate(): string;
}

33
types/utils/RagfairOfferHolder.d.ts vendored Normal file
View File

@@ -0,0 +1,33 @@
import { ProfileHelper } from "@spt/helpers/ProfileHelper";
import { RagfairServerHelper } from "@spt/helpers/RagfairServerHelper";
import { IRagfairOffer } from "@spt/models/eft/ragfair/IRagfairOffer";
export declare class RagfairOfferHolder {
protected maxOffersPerTemplate: number;
protected ragfairServerHelper: RagfairServerHelper;
protected profileHelper: ProfileHelper;
protected offersById: Map<string, IRagfairOffer>;
protected offersByTemplate: Map<string, Map<string, IRagfairOffer>>;
protected offersByTrader: Map<string, Map<string, IRagfairOffer>>;
constructor(maxOffersPerTemplate: number, ragfairServerHelper: RagfairServerHelper, profileHelper: ProfileHelper);
getOfferById(id: string): IRagfairOffer | undefined;
getOffersByTemplate(templateId: string): Array<IRagfairOffer> | undefined;
getOffersByTrader(traderId: string): Array<IRagfairOffer> | undefined;
getOffers(): Array<IRagfairOffer>;
addOffers(offers: Array<IRagfairOffer>): void;
addOffer(offer: IRagfairOffer): void;
/**
* Purge offer from offer cache
* @param offer Offer to remove
*/
removeOffer(offer: IRagfairOffer): void;
removeOffers(offers: Array<IRagfairOffer>): void;
removeAllOffersByTrader(traderId: string): void;
/**
* Get an array of stale offers that are still shown to player
* @returns IRagfairOffer array
*/
getStaleOffers(time: number): Array<IRagfairOffer>;
protected addOfferByTemplates(template: string, offer: IRagfairOffer): void;
protected addOfferByTrader(trader: string, offer: IRagfairOffer): void;
protected isStale(offer: IRagfairOffer, time: number): boolean;
}

182
types/utils/RandomUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,182 @@
import { ILogger } from "@spt/models/spt/utils/ILogger";
import { ICloner } from "@spt/utils/cloners/ICloner";
import { MathUtil } from "@spt/utils/MathUtil";
/**
* Array of ProbabilityObjectArray which allow to randomly draw of the contained objects
* based on the relative probability of each of its elements.
* The probabilities of the contained element is not required to be normalized.
*
* Example:
* po = new ProbabilityObjectArray(
* new ProbabilityObject("a", 5),
* new ProbabilityObject("b", 1),
* new ProbabilityObject("c", 1)
* );
* res = po.draw(10000);
* // count the elements which should be distributed according to the relative probabilities
* res.filter(x => x==="b").reduce((sum, x) => sum + 1 , 0)
*/
export declare class ProbabilityObjectArray<K, V = undefined> extends Array<ProbabilityObject<K, V>> {
private mathUtil;
private cloner;
constructor(mathUtil: MathUtil, cloner: ICloner, ...items: ProbabilityObject<K, V>[]);
filter(callbackfn: (value: ProbabilityObject<K, V>, index: number, array: ProbabilityObject<K, V>[]) => any): ProbabilityObjectArray<K, V>;
/**
* Calculates the normalized cumulative probability of the ProbabilityObjectArray's elements normalized to 1
* @param {array} probValues The relative probability values of which to calculate the normalized cumulative sum
* @returns {array} Cumulative Sum normalized to 1
*/
cumulativeProbability(probValues: number[]): number[];
/**
* Clone this ProbabilitObjectArray
* @returns {ProbabilityObjectArray} Deep Copy of this ProbabilityObjectArray
*/
clone(): ProbabilityObjectArray<K, V>;
/**
* Drop an element from the ProbabilityObjectArray
*
* @param {string} key The key of the element to drop
* @returns {ProbabilityObjectArray} ProbabilityObjectArray without the dropped element
*/
drop(key: K): ProbabilityObjectArray<K, V>;
/**
* Return the data field of a element of the ProbabilityObjectArray
* @param {string} key The key of the element whose data shall be retrieved
* @returns {object} The data object
*/
data(key: K): V | undefined;
/**
* Get the relative probability of an element by its key
*
* Example:
* po = new ProbabilityObjectArray(new ProbabilityObject("a", 5), new ProbabilityObject("b", 1))
* po.maxProbability() // returns 5
*
* @param {string} key The key of the element whose relative probability shall be retrieved
* @return {number} The relative probability
*/
probability(key: K): number;
/**
* Get the maximum relative probability out of a ProbabilityObjectArray
*
* Example:
* po = new ProbabilityObjectArray(new ProbabilityObject("a", 5), new ProbabilityObject("b", 1))
* po.maxProbability() // returns 5
*
* @return {number} the maximum value of all relative probabilities in this ProbabilityObjectArray
*/
maxProbability(): number;
/**
* Get the minimum relative probability out of a ProbabilityObjectArray
*
* Example:
* po = new ProbabilityObjectArray(new ProbabilityObject("a", 5), new ProbabilityObject("b", 1))
* po.minProbability() // returns 1
*
* @return {number} the minimum value of all relative probabilities in this ProbabilityObjectArray
*/
minProbability(): number;
/**
* Draw random element of the ProbabilityObject N times to return an array of N keys.
* Drawing can be with or without replacement
* @param count The number of times we want to draw
* @param replacement Draw with or without replacement from the input dict (true = dont remove after drawing)
* @param locklist list keys which shall be replaced even if drawing without replacement
* @returns Array consisting of N random keys for this ProbabilityObjectArray
*/
draw(count?: number, replacement?: boolean, locklist?: Array<K>): K[];
}
/**
* A ProbabilityObject which is use as an element to the ProbabilityObjectArray array
* It contains a key, the relative probability as well as optional data.
*/
export declare class ProbabilityObject<K, V = undefined> {
key: K;
relativeProbability: number;
data?: V;
/**
* Constructor for the ProbabilityObject
* @param {string} key The key of the element
* @param {number} relativeProbability The relative probability of this element
* @param {any} data Optional data attached to the element
*/
constructor(key: K, relativeProbability: number, data?: V);
}
export declare class RandomUtil {
protected cloner: ICloner;
protected logger: ILogger;
constructor(cloner: ICloner, logger: ILogger);
getInt(min: number, max: number): number;
getIntEx(max: number): number;
getFloat(min: number, max: number): number;
getBool(): boolean;
getPercentOfValue(percent: number, number: number, toFixed?: number): number;
/**
* Reduce a value by a percentage
* @param number Value to reduce
* @param percentage Percentage to reduce value by
* @returns Reduced value
*/
reduceValueByPercent(number: number, percentage: number): number;
/**
* Check if number passes a check out of 100
* @param chancePercent value check needs to be above
* @returns true if value passes check
*/
getChance100(chancePercent: number): boolean;
getStringArrayValue(arr: string[]): string;
getArrayValue<T>(arr: T[]): T;
getKey(node: any): string;
getKeyValue(node: {
[x: string]: any;
}): any;
/**
* Generate a normally distributed random number
* Uses the Box-Muller transform
* @param {number} mean Mean of the normal distribution
* @param {number} sigma Standard deviation of the normal distribution
* @returns {number} The value drawn
*/
getNormallyDistributedRandomNumber(mean: number, sigma: number, attempt?: number): number;
/**
* Draw Random integer low inclusive, high exclusive
* if high is not set we draw from 0 to low (exclusive)
* @param {integer} low Lower bound inclusive, when high is not set, this is high
* @param {integer} high Higher bound exclusive
* @returns {integer} The random integer in [low, high)
*/
randInt(low: number, high?: number): number;
/**
* Draw a random element of the provided list N times to return an array of N random elements
* Drawing can be with or without replacement
* @param {array} list The array we want to draw randomly from
* @param {integer} count The number of times we want to draw
* @param {boolean} replacement Draw with or without replacement from the input array(default true)
* @return {array} Array consisting of N random elements
*/
drawRandomFromList<T>(originalList: Array<T>, count?: number, replacement?: boolean): Array<T>;
/**
* Draw a random (top level) element of the provided dictionary N times to return an array of N random dictionary keys
* Drawing can be with or without replacement
* @param {any} dict The dictionary we want to draw randomly from
* @param {integer} count The number of times we want to draw
* @param {boolean} replacement Draw with ot without replacement from the input dict
* @return {array} Array consisting of N random keys of the dictionary
*/
drawRandomFromDict(dict: any, count?: number, replacement?: boolean): any[];
getBiasedRandomNumber(min: number, max: number, shift: number, n: number): number;
/**
* Fisher-Yates shuffle an array
* @param array Array to shuffle
* @returns Shuffled array
*/
shuffle<T>(array: Array<T>): Array<T>;
/**
* Rolls for a probability based on chance
* @param number Probability Chance as float (0-1)
* @returns If roll succeed or not
* @example
* rollForChanceProbability(0.25); // returns true 25% probability
*/
rollForChanceProbability(probabilityChance: number): boolean;
}

70
types/utils/TimeUtil.d.ts vendored Normal file
View File

@@ -0,0 +1,70 @@
/**
* Utility class to handle time related operations.
*/
export declare class TimeUtil {
static readonly ONE_HOUR_AS_SECONDS = 3600;
/**
* Pads a number with a leading zero if it is less than 10.
*
* @param {number} number - The number to pad.
* @returns {string} The padded number as a string.
*/
protected pad(number: number): string;
/**
* Formats the time part of a date as a UTC string.
*
* @param {Date} date - The date to format in UTC.
* @returns {string} The formatted time as 'HH-MM-SS'.
*/
formatTime(date: Date): string;
/**
* Formats the date part of a date as a UTC string.
*
* @param {Date} date - The date to format in UTC.
* @returns {string} The formatted date as 'YYYY-MM-DD'.
*/
formatDate(date: Date): string;
/**
* Gets the current date as a formatted UTC string.
*
* @returns {string} The current date as 'YYYY-MM-DD'.
*/
getDate(): string;
/**
* Gets the current time as a formatted UTC string.
*
* @returns {string} The current time as 'HH-MM-SS'.
*/
getTime(): string;
/**
* Gets the current timestamp in seconds in UTC.
*
* @returns {number} The current timestamp in seconds since the Unix epoch in UTC.
*/
getTimestamp(): number;
/**
* Get timestamp of today + passed in day count
* @param daysFromNow Days from now
*/
getTimeStampFromNowDays(daysFromNow: number): number;
/**
* Gets the current time in UTC in a format suitable for mail in EFT.
*
* @returns {string} The current time as 'HH:MM' in UTC.
*/
getTimeMailFormat(): string;
/**
* Gets the current date in UTC in a format suitable for emails in EFT.
*
* @returns {string} The current date as 'DD.MM.YYYY' in UTC.
*/
getDateMailFormat(): string;
/**
* Converts a number of hours into seconds.
*
* @param {number} hours - The number of hours to convert.
* @returns {number} The equivalent number of seconds.
*/
getHoursAsSeconds(hours: number): number;
getTimestampOfNextHour(): number;
}

57
types/utils/VFS.d.ts vendored Normal file
View File

@@ -0,0 +1,57 @@
/// <reference types="node" />
/// <reference types="node" />
import "reflect-metadata";
import fs from "node:fs";
import { IAsyncQueue } from "@spt/models/spt/utils/IAsyncQueue";
export declare class VFS {
protected asyncQueue: IAsyncQueue;
accessFilePromisify: (path: fs.PathLike, mode?: number) => Promise<void>;
copyFilePromisify: (src: fs.PathLike, dst: fs.PathLike, flags?: number) => Promise<void>;
mkdirPromisify: (path: fs.PathLike, options: fs.MakeDirectoryOptions & {
recursive: true;
}) => Promise<string | undefined>;
readFilePromisify: (path: fs.PathLike) => Promise<Buffer>;
writeFilePromisify: (path: fs.PathLike, data: string, options?: any) => Promise<void>;
readdirPromisify: (path: fs.PathLike, options?: BufferEncoding | {
encoding: BufferEncoding;
withFileTypes?: false;
}) => Promise<string[]>;
statPromisify: (path: fs.PathLike, options?: fs.StatOptions & {
bigint?: false;
}) => Promise<fs.Stats>;
unlinkPromisify: (path: fs.PathLike) => Promise<void>;
rmdirPromisify: (path: fs.PathLike) => Promise<void>;
renamePromisify: (oldPath: fs.PathLike, newPath: fs.PathLike) => Promise<void>;
constructor(asyncQueue: IAsyncQueue);
exists(filepath: fs.PathLike): boolean;
existsAsync(filepath: fs.PathLike): Promise<boolean>;
copyFile(filepath: fs.PathLike, target: fs.PathLike): void;
copyAsync(filepath: fs.PathLike, target: fs.PathLike): Promise<void>;
createDir(filepath: string): void;
createDirAsync(filepath: string): Promise<void>;
copyDir(filepath: string, target: string, fileExtensions?: string | string[]): void;
copyDirAsync(filepath: string, target: string, fileExtensions: string | string[]): Promise<void>;
readFile(...args: Parameters<typeof fs.readFileSync>): string;
readFileAsync(path: fs.PathLike): Promise<string>;
private isBuffer;
writeFile(filepath: any, data?: string, append?: boolean, atomic?: boolean): void;
writeFileAsync(filepath: any, data?: string, append?: boolean, atomic?: boolean): Promise<void>;
getFiles(filepath: string): string[];
getFilesAsync(filepath: string): Promise<string[]>;
getDirs(filepath: string): string[];
getDirsAsync(filepath: string): Promise<string[]>;
removeFile(filepath: string): void;
removeFileAsync(filepath: string): Promise<void>;
removeDir(filepath: string): void;
removeDirAsync(filepath: string): Promise<void>;
rename(oldPath: string, newPath: string): void;
renameAsync(oldPath: string, newPath: string): Promise<void>;
protected lockFileSync(filepath: any): () => void;
protected checkFileSync(filepath: any): boolean;
protected unlockFileSync(filepath: any): void;
getFileExtension(filepath: string): string | undefined;
stripExtension(filepath: string): string;
minifyAllJsonInDirRecursive(filepath: string): Promise<void>;
minifyAllJsonInDirRecursiveAsync(filepath: string): Promise<void>;
getFilesOfType(directory: string, fileType: string, files?: string[]): string[];
}

43
types/utils/Watermark.d.ts vendored Normal file
View File

@@ -0,0 +1,43 @@
import { ICoreConfig } from "@spt/models/spt/config/ICoreConfig";
import { ILogger } from "@spt/models/spt/utils/ILogger";
import { ConfigServer } from "@spt/servers/ConfigServer";
import { LocalisationService } from "@spt/services/LocalisationService";
export declare class WatermarkLocale {
protected localisationService: LocalisationService;
protected description: string[];
protected warning: string[];
protected modding: string[];
constructor(localisationService: LocalisationService);
getDescription(): string[];
getWarning(): string[];
getModding(): string[];
}
export declare class Watermark {
protected logger: ILogger;
protected configServer: ConfigServer;
protected localisationService: LocalisationService;
protected watermarkLocale: WatermarkLocale;
protected sptConfig: ICoreConfig;
protected text: string[];
protected versionLabel: string;
constructor(logger: ILogger, configServer: ConfigServer, localisationService: LocalisationService, watermarkLocale: WatermarkLocale);
initialize(): void;
/**
* Get a version string (x.x.x) or (x.x.x-BLEEDINGEDGE) OR (X.X.X (18xxx))
* @param withEftVersion Include the eft version this spt version was made for
* @returns string
*/
getVersionTag(withEftVersion?: boolean): string;
/**
* Handle singleplayer/settings/version
* Get text shown in game on screen, can't be translated as it breaks bsgs client when certian characters are used
* @returns string
*/
getInGameVersionLabel(): string;
/** Set window title */
protected setTitle(): void;
/** Reset console cursor to top */
protected resetCursor(): void;
/** Draw the watermark */
protected draw(): void;
}

3
types/utils/cloners/ICloner.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
export interface ICloner {
clone<T>(obj: T): T;
}

4
types/utils/cloners/JsonCloner.d.ts vendored Normal file
View File

@@ -0,0 +1,4 @@
import type { ICloner } from "@spt/utils/cloners/ICloner";
export declare class JsonCloner implements ICloner {
clone<T>(obj: T): T;
}

View File

@@ -0,0 +1,5 @@
import type { ICloner } from "@spt/utils/cloners/ICloner";
export declare class RecursiveCloner implements ICloner {
private static primitives;
clone<T>(obj: T): T;
}

View File

@@ -0,0 +1,4 @@
import type { ICloner } from "@spt/utils/cloners/ICloner";
export declare class StructuredCloner implements ICloner {
clone<T>(obj: T): T;
}

View File

@@ -0,0 +1,56 @@
export declare class LinkedList<T> {
private head?;
private tail?;
private _length;
get length(): number;
private set length(value);
constructor();
/**
* Adds an element to the start of the list.
*/
prepend(value: T): void;
/**
* Adds an element at the given index to the list.
*/
insertAt(value: T, idx: number): void;
/**
* Adds an element to the end of the list.
*/
append(value: T): void;
/**
* Returns the first element's value.
*/
getHead(): T | undefined;
/**
* Finds the element from the list at the given index and returns it's value.
*/
get(idx: number): T | undefined;
/**
* Returns the last element's value.
*/
getTail(): T | undefined;
/**
* Finds and removes the first element from a list that has a value equal to the given value, returns it's value if it successfully removed it.
*/
remove(value: T): T | undefined;
/**
* Removes the first element from the list and returns it's value. If the list is empty, undefined is returned and the list is not modified.
*/
shift(): T | undefined;
/**
* Removes the element from the list at the given index and returns it's value.
*/
removeAt(idx: number): T | undefined;
/**
* Removes the last element from the list and returns it's value. If the list is empty, undefined is returned and the list is not modified.
*/
pop(): T | undefined;
/**
* Returns an iterable of index, value pairs for every entry in the list.
*/
entries(): IterableIterator<[number, T | undefined]>;
/**
* Returns an iterable of values in the list.
*/
values(): IterableIterator<T>;
}

View File

@@ -0,0 +1,6 @@
export declare class LinkedListNode<T> {
value: T;
prev?: LinkedListNode<T>;
next?: LinkedListNode<T>;
constructor(value: T, prev?: LinkedListNode<T>, next?: LinkedListNode<T>);
}

View File

@@ -0,0 +1,21 @@
export declare class Queue<T> {
private list;
get length(): number;
constructor();
/**
* Adds an element to the end of the queue.
*/
enqueue(element: T): void;
/**
* Iterates over the elements received and adds each one to the end of the queue.
*/
enqueueAll(elements: T[]): void;
/**
* Removes the first element from the queue and returns it's value. If the queue is empty, undefined is returned and the queue is not modified.
*/
dequeue(): T | undefined;
/**
* Returns the first element's value.
*/
peek(): T | undefined;
}

View File

@@ -0,0 +1,68 @@
/// <reference types="node" />
import fs from "node:fs";
import winston from "winston";
import { Daum } from "@spt/models/eft/itemEvent/IItemEventRouterRequest";
import { LogBackgroundColor } from "@spt/models/spt/logging/LogBackgroundColor";
import { LogTextColor } from "@spt/models/spt/logging/LogTextColor";
import { SptLogger } from "@spt/models/spt/logging/SptLogger";
import { IAsyncQueue } from "@spt/models/spt/utils/IAsyncQueue";
import { ILogger } from "@spt/models/spt/utils/ILogger";
export declare abstract class AbstractWinstonLogger implements ILogger {
protected asyncQueue: IAsyncQueue;
protected showDebugInConsole: boolean;
protected filePath: string;
protected logLevels: {
levels: {
error: number;
warn: number;
succ: number;
info: number;
custom: number;
debug: number;
};
colors: {
error: string;
warn: string;
succ: string;
info: string;
custom: string;
debug: string;
};
bgColors: {
default: string;
blackBG: string;
redBG: string;
greenBG: string;
yellowBG: string;
blueBG: string;
magentaBG: string;
cyanBG: string;
whiteBG: string;
};
};
protected logger: winston.Logger & SptLogger;
protected writeFilePromisify: (path: fs.PathLike, data: string, options?: any) => Promise<void>;
constructor(asyncQueue: IAsyncQueue);
protected abstract isLogToFile(): boolean;
protected abstract isLogToConsole(): boolean;
protected abstract isLogExceptions(): boolean;
protected abstract getFilePath(): string;
protected abstract getFileName(): string;
protected getLogFrequency(): string;
protected getLogMaxSize(): string;
protected getLogMaxFiles(): string;
writeToLogFile(data: string | Daum): Promise<void>;
log(data: string | Error | Record<string, unknown>, color: string, backgroundColor?: string): Promise<void>;
error(data: string | Record<string, unknown>): Promise<void>;
warning(data: string | Record<string, unknown>): Promise<void>;
success(data: string | Record<string, unknown>): Promise<void>;
info(data: string | Record<string, unknown>): Promise<void>;
/**
* Log to console text with a customisable text and background color. Background defaults to black
* @param data text to log
* @param textColor color of text
* @param backgroundColor color of background
*/
logWithColor(data: string | Record<string, unknown>, textColor: LogTextColor, backgroundColor?: LogBackgroundColor): Promise<void>;
debug(data: string | Record<string, unknown>, onlyShowInConsole?: boolean): Promise<void>;
}

View File

@@ -0,0 +1,11 @@
import { IAsyncQueue } from "@spt/models/spt/utils/IAsyncQueue";
import { AbstractWinstonLogger } from "@spt/utils/logging/AbstractWinstonLogger";
export declare class WinstonMainLogger extends AbstractWinstonLogger {
protected asyncQueue: IAsyncQueue;
constructor(asyncQueue: IAsyncQueue);
protected isLogExceptions(): boolean;
protected isLogToFile(): boolean;
protected isLogToConsole(): boolean;
protected getFilePath(): string;
protected getFileName(): string;
}

View File

@@ -0,0 +1,12 @@
import { IAsyncQueue } from "@spt/models/spt/utils/IAsyncQueue";
import { AbstractWinstonLogger } from "@spt/utils/logging/AbstractWinstonLogger";
export declare class WinstonRequestLogger extends AbstractWinstonLogger {
protected asyncQueue: IAsyncQueue;
constructor(asyncQueue: IAsyncQueue);
protected isLogExceptions(): boolean;
protected isLogToFile(): boolean;
protected isLogToConsole(): boolean;
protected getFilePath(): string;
protected getFileName(): string;
protected getLogMaxSize(): string;
}