@sv443-network/coreutils 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/LICENSE.txt +21 -0
- package/README.md +141 -0
- package/dist/CoreUtils.cjs +1213 -0
- package/dist/CoreUtils.min.cjs +4 -0
- package/dist/CoreUtils.min.mjs +4 -0
- package/dist/CoreUtils.min.umd.js +46 -0
- package/dist/CoreUtils.mjs +1180 -0
- package/dist/CoreUtils.umd.js +1255 -0
- package/dist/lib/DataStore.d.ts +159 -0
- package/dist/lib/DataStoreEngine.d.ts +89 -0
- package/dist/lib/DataStoreSerializer.d.ts +116 -0
- package/dist/lib/Debouncer.d.ts +86 -0
- package/dist/lib/Errors.d.ts +21 -0
- package/dist/lib/NanoEmitter.d.ts +71 -0
- package/dist/lib/TieredCache.d.ts +86 -0
- package/dist/lib/Translate.d.ts +65 -0
- package/dist/lib/array.d.ts +19 -0
- package/dist/lib/colors.d.ts +27 -0
- package/dist/lib/crypto.d.ts +34 -0
- package/dist/lib/index.d.ts +17 -0
- package/dist/lib/math.d.ts +61 -0
- package/dist/lib/misc.d.ts +65 -0
- package/dist/lib/text.d.ts +41 -0
- package/dist/lib/types.d.ts +44 -0
- package/package.json +86 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module Translate
|
|
3
|
+
* This module contains a sophisticated but still lightweight, JSON-based translation system - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-translate)
|
|
4
|
+
*/
|
|
5
|
+
import type { Stringifiable } from "./types.js";
|
|
6
|
+
/**
|
|
7
|
+
* Translation object to pass to {@linkcode tr.addTranslations()}
|
|
8
|
+
* Can be a flat object of identifier keys and the translation text as the value, or an infinitely nestable object containing the same.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* // Flat object:
|
|
12
|
+
* const tr_en: TrObject = {
|
|
13
|
+
* hello: "Hello, %1!",
|
|
14
|
+
* foo: "Foo",
|
|
15
|
+
* };
|
|
16
|
+
*
|
|
17
|
+
* // Nested object:
|
|
18
|
+
* const tr_de: TrObject = {
|
|
19
|
+
* hello: "Hallo, %1!",
|
|
20
|
+
* foo: {
|
|
21
|
+
* bar: "Foo bar",
|
|
22
|
+
* },
|
|
23
|
+
* };
|
|
24
|
+
*/
|
|
25
|
+
export interface TrObject {
|
|
26
|
+
[key: string]: string | TrObject;
|
|
27
|
+
}
|
|
28
|
+
/** Properties for the transform function that transforms a matched translation string into something else */
|
|
29
|
+
export type TransformFnProps<TTrKey extends string = string> = {
|
|
30
|
+
/** The currently set language - empty string if not set yet */
|
|
31
|
+
language: string;
|
|
32
|
+
/** The matches as returned by `RegExp.exec()` */
|
|
33
|
+
matches: RegExpExecArray[];
|
|
34
|
+
/** The translation key */
|
|
35
|
+
trKey: TTrKey;
|
|
36
|
+
/** Translation value before any transformations */
|
|
37
|
+
trValue: string;
|
|
38
|
+
/** Current value, possibly in-between transformations */
|
|
39
|
+
currentValue: string;
|
|
40
|
+
/** Arguments passed to the translation function */
|
|
41
|
+
trArgs: (Stringifiable | Record<string, Stringifiable>)[];
|
|
42
|
+
};
|
|
43
|
+
/** Function that transforms a matched translation string into another string */
|
|
44
|
+
export type TransformFn<TTrKey extends string = string> = (props: TransformFnProps<TTrKey>) => Stringifiable;
|
|
45
|
+
/**
|
|
46
|
+
* Pass a nested or flat translation object to this generic type to recursively get all keys in the object.
|
|
47
|
+
* @example ```ts
|
|
48
|
+
* type Keys = TrKeys<{ a: { b: { c: "bar" }, d: "foo" }, e: "baz" }>;
|
|
49
|
+
* // ^? type Keys = "a.b.c" | "a.d" | "e"
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export type TrKeys<TTrObj, P extends string = ""> = {
|
|
53
|
+
[K in keyof TTrObj]: K extends string | number | boolean | null | undefined ? TTrObj[K] extends object ? TrKeys<TTrObj[K], `${P}${K}.`> : `${P}${K}` : never;
|
|
54
|
+
}[keyof TTrObj];
|
|
55
|
+
/** Options for the {@linkcode Translate} class */
|
|
56
|
+
export type TranslateOptions = {};
|
|
57
|
+
/**
|
|
58
|
+
* Class that manages translations, provides many utility functions, handles fallbacks and allows you to specify custom transforms to insert values or modify the translation string in pretty much any way imaginable.
|
|
59
|
+
*/
|
|
60
|
+
export declare class Translate {
|
|
61
|
+
readonly options: TranslateOptions;
|
|
62
|
+
/** All translations loaded into memory */
|
|
63
|
+
protected translations: Record<string, TrObject>;
|
|
64
|
+
constructor(options: TranslateOptions);
|
|
65
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module array
|
|
3
|
+
* This module contains various functions for working with arrays - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#arrays)
|
|
4
|
+
*/
|
|
5
|
+
/** Describes an array with at least one item */
|
|
6
|
+
export type NonEmptyArray<TArray = unknown> = [TArray, ...TArray[]];
|
|
7
|
+
/** Returns a random item from the passed array */
|
|
8
|
+
export declare function randomItem<TItem = unknown>(array: TItem[]): TItem | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Returns a tuple of a random item and its index from the passed array
|
|
11
|
+
* Returns `[undefined, undefined]` if the passed array is empty
|
|
12
|
+
*/
|
|
13
|
+
export declare function randomItemIndex<TItem = unknown>(array: TItem[]): [item?: TItem, index?: number];
|
|
14
|
+
/** Returns a copy of the array with its items in a random order */
|
|
15
|
+
export declare function randomizeArray<TItem = unknown>(array: TItem[]): TItem[];
|
|
16
|
+
/** Returns a random item from the passed array and mutates the array to remove the item */
|
|
17
|
+
export declare function takeRandomItem<TItem = unknown>(arr: TItem[]): TItem | undefined;
|
|
18
|
+
/** Returns a random item and its index as a tuple from the passed array and mutates the array to remove the item */
|
|
19
|
+
export declare function takeRandomItemIndex<TItem = unknown>(arr: TItem[]): [item?: TItem, index?: number];
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module colors
|
|
3
|
+
* This module contains various functions for working with colors - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#colors)
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Darkens a CSS color value (in `#HEX`, `HEX`, `rgb()` or `rgba()` format) by a given percentage.
|
|
7
|
+
* Will not exceed the maximum range (`00-FF` / `0-255`).
|
|
8
|
+
* The alpha value is not changed.
|
|
9
|
+
* @returns Returns the new color value in the same format as the input
|
|
10
|
+
* @throws Throws if the color format is invalid or not supported
|
|
11
|
+
*/
|
|
12
|
+
export declare function darkenColor(color: string, percent: number, upperCase?: boolean): string;
|
|
13
|
+
/**
|
|
14
|
+
* Converts a hex color string in the format `#RRGGBB`, `#RRGGBBAA` (or even `RRGGBB` and `RGB`) to a tuple.
|
|
15
|
+
* @returns Returns a tuple array where R, G and B are an integer in the range `0-255` and alpha is a float in the range `0-1`, or `undefined` if no alpha channel exists.
|
|
16
|
+
*/
|
|
17
|
+
export declare function hexToRgb(hex: string): [red: number, green: number, blue: number, alpha?: number];
|
|
18
|
+
/**
|
|
19
|
+
* Lightens a CSS color value (in `#HEX`, `HEX`, `rgb()` or `rgba()` format) by a given percentage.
|
|
20
|
+
* Will not exceed the maximum range (`00-FF` / `0-255`).
|
|
21
|
+
* The alpha value is not changed.
|
|
22
|
+
* @returns Returns the new color value in the same format as the input
|
|
23
|
+
* @throws Throws if the color format is invalid or not supported
|
|
24
|
+
*/
|
|
25
|
+
export declare function lightenColor(color: string, percent: number, upperCase?: boolean): string;
|
|
26
|
+
/** Converts RGB or RGBA number values to a hex color string in the format `#RRGGBB` or `#RRGGBBAA` */
|
|
27
|
+
export declare function rgbToHex(red: number, green: number, blue: number, alpha?: number, withHash?: boolean, upperCase?: boolean): string;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module crypto
|
|
3
|
+
* This module contains various cryptographic functions, like compression and ArrayBuffer encoding - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#crypto)
|
|
4
|
+
*/
|
|
5
|
+
import type { Stringifiable } from "./types.js";
|
|
6
|
+
/** Converts an ArrayBuffer to a base64-encoded (ASCII) string */
|
|
7
|
+
export declare function abtoa(buf: ArrayBuffer): string;
|
|
8
|
+
/** Converts a base64-encoded (ASCII) string to an ArrayBuffer representation of its bytes */
|
|
9
|
+
export declare function atoab(str: string): ArrayBuffer;
|
|
10
|
+
/** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as a base64 string */
|
|
11
|
+
export declare function compress(input: Stringifiable | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>;
|
|
12
|
+
/** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as an ArrayBuffer */
|
|
13
|
+
export declare function compress(input: Stringifiable | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>;
|
|
14
|
+
/** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to a string */
|
|
15
|
+
export declare function decompress(input: Stringifiable | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>;
|
|
16
|
+
/** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to an ArrayBuffer */
|
|
17
|
+
export declare function decompress(input: Stringifiable | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>;
|
|
18
|
+
/**
|
|
19
|
+
* Creates a hash / checksum of the given {@linkcode input} string or ArrayBuffer using the specified {@linkcode algorithm} ("SHA-256" by default).
|
|
20
|
+
*
|
|
21
|
+
* - ⚠️ Uses the SubtleCrypto API so it needs to run in a secure context (HTTPS).
|
|
22
|
+
* - ⚠️ If you use this for cryptography, make sure to use a secure algorithm (under no circumstances use SHA-1) and to [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) your input data.
|
|
23
|
+
*/
|
|
24
|
+
export declare function computeHash(input: string | ArrayBuffer, algorithm?: string): Promise<string>;
|
|
25
|
+
/**
|
|
26
|
+
* Generates a random ID with the specified length and radix (16 characters and hexadecimal by default)
|
|
27
|
+
*
|
|
28
|
+
* - ⚠️ Not suitable for generating anything related to cryptography! Use [SubtleCrypto's `generateKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) for that instead.
|
|
29
|
+
* @param length The length of the ID to generate (defaults to 16)
|
|
30
|
+
* @param radix The [radix](https://en.wikipedia.org/wiki/Radix) of each digit (defaults to 16 which is hexadecimal. Use 2 for binary, 10 for decimal, 36 for alphanumeric, etc.)
|
|
31
|
+
* @param enhancedEntropy If set to true, uses [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) for better cryptographic randomness (this also makes it take longer to generate)
|
|
32
|
+
* @param randomCase If set to false, the generated ID will be lowercase only - also makes use of the `enhancedEntropy` parameter unless the output doesn't contain letters
|
|
33
|
+
*/
|
|
34
|
+
export declare function randomId(length?: number, radix?: number, enhancedEntropy?: boolean, randomCase?: boolean): string;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @sv443-network/coreutils
|
|
3
|
+
* @description Cross-platform, general-purpose, JavaScript core library for Node, Deno and the browser. Intended to be used in conjunction with [`@sv443-network/userutils`](https://github.com/Sv443-Network/UserUtils) and [`@sv443-network/djsutils`](https://github.com/Sv443-Network/DJSUtils), but can be used independently as well.
|
|
4
|
+
*/
|
|
5
|
+
export * from "./array.js";
|
|
6
|
+
export * from "./colors.js";
|
|
7
|
+
export * from "./crypto.js";
|
|
8
|
+
export * from "./math.js";
|
|
9
|
+
export * from "./misc.js";
|
|
10
|
+
export * from "./text.js";
|
|
11
|
+
export * from "./types.js";
|
|
12
|
+
export * from "./DataStore.js";
|
|
13
|
+
export * from "./DataStoreEngine.js";
|
|
14
|
+
export * from "./DataStoreSerializer.js";
|
|
15
|
+
export * from "./Debouncer.js";
|
|
16
|
+
export * from "./Errors.js";
|
|
17
|
+
export * from "./NanoEmitter.js";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module math
|
|
3
|
+
* This module contains general-purpose math functions like clamping, mapping and random number generation - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#math)
|
|
4
|
+
*/
|
|
5
|
+
import type { NumberFormat, Stringifiable } from "./types.js";
|
|
6
|
+
/** Checks if the given {@linkcode bitSet} contains the given {@linkcode checkVal} */
|
|
7
|
+
export declare function bitSetHas<TType extends number | bigint>(bitSet: TType, checkVal: TType): boolean;
|
|
8
|
+
/** Ensures the passed {@linkcode value} always stays between {@linkcode min} and {@linkcode max} */
|
|
9
|
+
export declare function clamp(value: number, min: number, max: number): number;
|
|
10
|
+
/** Ensures the passed {@linkcode value} always stays between 0 and {@linkcode max} */
|
|
11
|
+
export declare function clamp(value: number, max: number): number;
|
|
12
|
+
/**
|
|
13
|
+
* Calculates the amount of digits in the given number - the given number or string will be passed to the `Number()` constructor.
|
|
14
|
+
* Returns NaN if the number is invalid.
|
|
15
|
+
* @param num The number to count the digits of
|
|
16
|
+
* @param withDecimals Whether to count the decimal places as well (defaults to true)
|
|
17
|
+
* @example ```ts
|
|
18
|
+
* digitCount(); // NaN
|
|
19
|
+
* digitCount(123); // 3
|
|
20
|
+
* digitCount(1.23); // 3
|
|
21
|
+
* digitCount(1.23, false); // 1
|
|
22
|
+
* digitCount(Infinity); // Infinity
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare function digitCount(num: number | Stringifiable, withDecimals?: boolean): number;
|
|
26
|
+
/** Formats a number with the given locale and format */
|
|
27
|
+
export declare function formatNumber(number: number, locale: string, format: NumberFormat): string;
|
|
28
|
+
/**
|
|
29
|
+
* Transforms the value parameter from the numerical range `range1min` to `range1max` to the numerical range `range2min` to `range2max`
|
|
30
|
+
* For example, you can map the value 2 in the range of 0-5 to the range of 0-10 and you'd get a 4 as a result.
|
|
31
|
+
*/
|
|
32
|
+
export declare function mapRange(value: number, range1min: number, range1max: number, range2min: number, range2max: number): number;
|
|
33
|
+
/**
|
|
34
|
+
* Transforms the value parameter from the numerical range `0` to `range1max` to the numerical range `0` to `range2max`
|
|
35
|
+
* For example, you can map the value 2 in the range of 0-5 to the range of 0-10 and you'd get a 4 as a result.
|
|
36
|
+
*/
|
|
37
|
+
export declare function mapRange(value: number, range1max: number, range2max: number): number;
|
|
38
|
+
/**
|
|
39
|
+
* Returns a random number between {@linkcode min} and {@linkcode max} (inclusive)
|
|
40
|
+
* Set {@linkcode enhancedEntropy} to true to use `crypto.getRandomValues()` for better cryptographic randomness (this also makes it take longer to generate)
|
|
41
|
+
*/
|
|
42
|
+
export declare function randRange(min: number, max: number, enhancedEntropy?: boolean): number;
|
|
43
|
+
/**
|
|
44
|
+
* Returns a random number between 0 and {@linkcode max} (inclusive)
|
|
45
|
+
* Set {@linkcode enhancedEntropy} to true to use `crypto.getRandomValues()` for better cryptographic randomness (this also makes it take longer to generate)
|
|
46
|
+
*/
|
|
47
|
+
export declare function randRange(max: number, enhancedEntropy?: boolean): number;
|
|
48
|
+
/**
|
|
49
|
+
* Rounds {@linkcode num} to a fixed amount of decimal places, specified by {@linkcode fractionDigits} (supports negative values to round to the nearest power of 10).
|
|
50
|
+
* @example ```ts
|
|
51
|
+
* roundFixed(234.567, -2); // 200
|
|
52
|
+
* roundFixed(234.567, -1); // 230
|
|
53
|
+
* roundFixed(234.567, 0); // 235
|
|
54
|
+
* roundFixed(234.567, 1); // 234.6
|
|
55
|
+
* roundFixed(234.567, 2); // 234.57
|
|
56
|
+
* roundFixed(234.567, 3); // 234.567
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare function roundFixed(num: number, fractionDigits: number): number;
|
|
60
|
+
/** Rounds the given values at the given decimal place (same as in {@linkcode roundFixed()}) and checks if they are within the given range (0.5 by default) */
|
|
61
|
+
export declare function valsWithin(a: number, b: number, dec?: number, withinRange?: number): boolean;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module misc
|
|
3
|
+
* This module contains miscellaneous functions that don't fit in another category - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#misc)
|
|
4
|
+
*/
|
|
5
|
+
import type { ListLike, Prettify, Stringifiable } from "./types.js";
|
|
6
|
+
/**
|
|
7
|
+
* A ValueGen value is either its type, a promise that resolves to its type, or a function that returns its type, either synchronous or asynchronous.
|
|
8
|
+
* ValueGen allows for the utmost flexibility when applied to any type, as long as {@linkcode consumeGen()} is used to get the final value.
|
|
9
|
+
* @template TValueType The type of the value that the ValueGen should yield
|
|
10
|
+
*/
|
|
11
|
+
export type ValueGen<TValueType> = TValueType | Promise<TValueType> | (() => TValueType | Promise<TValueType>);
|
|
12
|
+
/**
|
|
13
|
+
* Turns a {@linkcode ValueGen} into its final value.
|
|
14
|
+
* @template TValueType The type of the value that the ValueGen should yield
|
|
15
|
+
*/
|
|
16
|
+
export declare function consumeGen<TValueType>(valGen: ValueGen<TValueType>): Promise<TValueType>;
|
|
17
|
+
/**
|
|
18
|
+
* A StringGen value is either a string, anything that can be converted to a string, or a function that returns one of the previous two, either synchronous or asynchronous, or a promise that returns a string.
|
|
19
|
+
* StringGen allows for the utmost flexibility when dealing with strings, as long as {@linkcode consumeStringGen()} is used to get the final string.
|
|
20
|
+
*/
|
|
21
|
+
export type StringGen = ValueGen<Stringifiable>;
|
|
22
|
+
/**
|
|
23
|
+
* Turns a {@linkcode StringGen} into its final string value.
|
|
24
|
+
* @template TStrUnion The union of strings that the StringGen should yield - this allows for finer type control compared to {@linkcode consumeGen()}
|
|
25
|
+
*/
|
|
26
|
+
export declare function consumeStringGen<TStrUnion extends string>(strGen: StringGen): Promise<TStrUnion>;
|
|
27
|
+
/** Options for the `fetchAdvanced()` function */
|
|
28
|
+
export type FetchAdvancedOpts = Prettify<Partial<{
|
|
29
|
+
/** Timeout in milliseconds after which the fetch call will be canceled with an AbortController signal */
|
|
30
|
+
timeout: number;
|
|
31
|
+
}> & RequestInit>;
|
|
32
|
+
/** Calls the fetch API with special options like a timeout */
|
|
33
|
+
export declare function fetchAdvanced(input: string | RequestInfo | URL, options?: FetchAdvancedOpts): Promise<Response>;
|
|
34
|
+
/**
|
|
35
|
+
* Returns the length of the given list-like object (anything with a numeric `length`, `size` or `count` property, like an array, Map or NodeList).
|
|
36
|
+
* If the object doesn't have any of these properties, it will return 0 by default.
|
|
37
|
+
* Set {@linkcode zeroOnInvalid} to false to return NaN instead of 0 if the object doesn't have any of the properties.
|
|
38
|
+
*/
|
|
39
|
+
export declare function getListLength(listLike: ListLike, zeroOnInvalid?: boolean): number;
|
|
40
|
+
/**
|
|
41
|
+
* Pauses async execution for the specified time in ms.
|
|
42
|
+
* If an `AbortSignal` is passed, the pause will be aborted when the signal is triggered.
|
|
43
|
+
* By default, this will resolve the promise, but you can set {@linkcode rejectOnAbort} to true to reject it instead.
|
|
44
|
+
*/
|
|
45
|
+
export declare function pauseFor(time: number, signal?: AbortSignal, rejectOnAbort?: boolean): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Turns the passed object into a "pure" object without a prototype chain, meaning it won't have any default properties like `toString`, `__proto__`, `__defineGetter__`, etc.
|
|
48
|
+
* This makes the object immune to prototype pollution attacks and allows for cleaner object literals, at the cost of being harder to work with in some cases.
|
|
49
|
+
* It also effectively transforms a `Stringifiable` value into one that will throw a TypeError when stringified instead of defaulting to `[object Object]`
|
|
50
|
+
* If no object is passed, it will return an empty object without prototype chain.
|
|
51
|
+
*/
|
|
52
|
+
export declare function pureObj<TObj extends object>(obj?: TObj): TObj;
|
|
53
|
+
/**
|
|
54
|
+
* Works similarly to `setInterval()`, but the callback is also called immediately and can be aborted with an `AbortSignal`.
|
|
55
|
+
* Uses `setInterval()` internally, which might cause overlapping calls if the callback's synchronous execution takes longer than the given interval time.
|
|
56
|
+
* This function will prevent skewing the interval time, contrary to {@linkcode setImmediateTimeoutLoop()}.
|
|
57
|
+
* Returns a cleanup function that will stop the interval if called.
|
|
58
|
+
*/
|
|
59
|
+
export declare function setImmediateInterval(callback: () => void | unknown, interval: number, signal?: AbortSignal): void;
|
|
60
|
+
/**
|
|
61
|
+
* Works similarly to `setInterval()`, but the callback is also called immediately and can be aborted with an `AbortSignal`.
|
|
62
|
+
* Uses `setTimeout()` internally to avoid overlapping calls, though this will skew the given interval time by however long the callback takes to execute synchronously.
|
|
63
|
+
* Returns a cleanup function that will stop the interval if called.
|
|
64
|
+
*/
|
|
65
|
+
export declare function setImmediateTimeoutLoop(callback: () => void | unknown | Promise<void | unknown>, interval: number, signal?: AbortSignal): void;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ListLike, Prettify, Stringifiable } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Automatically pluralizes the given string an `-s` or `-ies` to the passed {@linkcode term}, if {@linkcode num} is not equal to 1.
|
|
4
|
+
* By default, words ending in `-y` will have it replaced with `-ies`, and all other words will simply have `-s` appended.
|
|
5
|
+
* If {@linkcode num} resolves to NaN or the {@linkcode pluralType} is wrong, it defaults to the {@linkcode pluralType} `auto` and sets {@linkcode num} to 2.
|
|
6
|
+
* @param term The term, written in singular form, to auto-convert to plural form
|
|
7
|
+
* @param num A number, or list-like value that has either a `length`, `count` or `size` property, like an array, Map or discord.js Collection - does not support iterables, they need to be converted to an array first
|
|
8
|
+
* @param pluralType Which plural form to use when auto-pluralizing. Defaults to `"auto"`, which removes the last char and uses `-ies` for words ending in `y` and simply appends `-s` for all other words
|
|
9
|
+
*/
|
|
10
|
+
export declare function autoPlural(term: Stringifiable, num: number | ListLike, pluralType?: "auto" | "-s" | "-ies"): string;
|
|
11
|
+
/** Capitalizes the first letter of a string */
|
|
12
|
+
export declare function capitalize(text: string): string;
|
|
13
|
+
/** The default progress bar characters used by {@linkcode createProgressBar()} */
|
|
14
|
+
export declare const defaultPbChars: {
|
|
15
|
+
readonly 100: "█";
|
|
16
|
+
readonly 75: "▓";
|
|
17
|
+
readonly 50: "▒";
|
|
18
|
+
readonly 25: "░";
|
|
19
|
+
readonly 0: "─";
|
|
20
|
+
};
|
|
21
|
+
/** Progress bar characters used by {@linkcode createProgressBar()} */
|
|
22
|
+
export type ProgressBarChars = Prettify<Record<keyof typeof defaultPbChars, string>>;
|
|
23
|
+
/**
|
|
24
|
+
* Generates a progress bar with the given percentage and max length.
|
|
25
|
+
* Uses opaque, dithered unicode block characters by default for extra detail.
|
|
26
|
+
* Use {@linkcode chars} to override the default characters (for example, use emojis via `<:emoji:ID>` or `😃`)
|
|
27
|
+
*/
|
|
28
|
+
export declare function createProgressBar(percentage: number, barLength: number, chars?: ProgressBarChars): string;
|
|
29
|
+
/**
|
|
30
|
+
* Inserts the passed values into a string at the respective placeholders.
|
|
31
|
+
* The placeholder format is `%n`, where `n` is the 1-indexed argument number.
|
|
32
|
+
* @param input The string to insert the values into
|
|
33
|
+
* @param values The values to insert, in order, starting at `%1`
|
|
34
|
+
*/
|
|
35
|
+
export declare function insertValues(input: string, ...values: Stringifiable[]): string;
|
|
36
|
+
/** Joins an array of strings with a separator and a last separator - defaults to `,` & `and` */
|
|
37
|
+
export declare function joinArrayReadable(array: unknown[], separators?: string, lastSeparator?: string): string;
|
|
38
|
+
/** Converts seconds into the timestamp format `(hh:)mm:ss`, with intelligent zero-padding */
|
|
39
|
+
export declare function secsToTimeStr(seconds: number): string;
|
|
40
|
+
/** Truncates a string if it exceeds `length` and inserts `endStr` at the end (empty string to disable), so that the final string doesn't exceed the given length */
|
|
41
|
+
export declare function truncStr(input: Stringifiable, length: number, endStr?: string): string;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module types
|
|
3
|
+
* This module contains various utility types - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#types)
|
|
4
|
+
*/
|
|
5
|
+
/** Any value that is list-like, i.e. has a quantifiable length, count or size property */
|
|
6
|
+
export type ListLike = unknown[] | {
|
|
7
|
+
length: number;
|
|
8
|
+
} | {
|
|
9
|
+
count: number;
|
|
10
|
+
} | {
|
|
11
|
+
size: number;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* A type that offers autocomplete for the passed union but also allows any arbitrary value of the same type to be passed.
|
|
15
|
+
* Supports unions of strings, numbers and objects.
|
|
16
|
+
*/
|
|
17
|
+
export type LooseUnion<TUnion extends string | number | object> = (TUnion) | (TUnion extends string ? (string & {}) : (TUnion extends number ? (number & {}) : (TUnion extends Record<keyof any, unknown> ? (object & {}) : never)));
|
|
18
|
+
/** Any class reference that can be instantiated with `new` */
|
|
19
|
+
export type Newable<T> = new (...args: any[]) => T;
|
|
20
|
+
/**
|
|
21
|
+
* A type that allows all strings except for empty ones
|
|
22
|
+
* @example
|
|
23
|
+
* function foo<T extends string>(bar: NonEmptyString<T>) {
|
|
24
|
+
* console.log(bar);
|
|
25
|
+
* }
|
|
26
|
+
*/
|
|
27
|
+
export type NonEmptyString<TString extends string> = TString extends "" ? never : TString;
|
|
28
|
+
/** String constant that decides which set of number formatting options to use */
|
|
29
|
+
export type NumberFormat = "short" | "long";
|
|
30
|
+
/**
|
|
31
|
+
* Makes the structure of a type more readable by expanding it.
|
|
32
|
+
* This can be useful for debugging or for improving the readability of complex types.
|
|
33
|
+
*/
|
|
34
|
+
export type Prettify<T> = {
|
|
35
|
+
[K in keyof T]: T[K];
|
|
36
|
+
} & {};
|
|
37
|
+
/** Any value that can be serialized to JSON */
|
|
38
|
+
export type SerializableVal = string | number | boolean | null | SerializableVal[] | {
|
|
39
|
+
[key: string]: SerializableVal;
|
|
40
|
+
};
|
|
41
|
+
/** Any value that can be implicitly converted to a string with `String(val)`, `val.toString()` or \``${val}`\` */
|
|
42
|
+
export type Stringifiable = string | number | boolean | null | undefined | {
|
|
43
|
+
toString(): string;
|
|
44
|
+
} | Stringifiable[];
|
package/package.json
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sv443-network/coreutils",
|
|
3
|
+
"libName": "@sv443-network/coreutils",
|
|
4
|
+
"version": "0.0.1",
|
|
5
|
+
"description": "",
|
|
6
|
+
"main": "dist/CoreUtils.cjs",
|
|
7
|
+
"module": "dist/CoreUtils.mjs",
|
|
8
|
+
"types": "dist/lib/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"browser": "./dist/CoreUtils.min.umd.js",
|
|
12
|
+
"types": "./dist/lib/index.d.ts",
|
|
13
|
+
"require": "./dist/CoreUtils.cjs",
|
|
14
|
+
"import": "./dist/CoreUtils.mjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"type": "module",
|
|
18
|
+
"scripts": {
|
|
19
|
+
"lint": "eslint . && tsc --noEmit",
|
|
20
|
+
"format": "eslint . --fix",
|
|
21
|
+
"build": "tsup",
|
|
22
|
+
"dev": "tsup --watch",
|
|
23
|
+
"update-jsr-version": "node --import tsx ./tools/update-jsr-version.mts",
|
|
24
|
+
"publish-package": "changeset publish",
|
|
25
|
+
"publish-package-jsr": "pnpm update-jsr-version && npx jsr publish --allow-dirty",
|
|
26
|
+
"check-jsr": "pnpm update-jsr-version && npx jsr publish --allow-dirty --dry-run",
|
|
27
|
+
"change": "changeset",
|
|
28
|
+
"test": "vitest",
|
|
29
|
+
"test-coverage": "vitest --coverage"
|
|
30
|
+
},
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/Sv443-Network/CoreUtils.git"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"userscript",
|
|
37
|
+
"utilities"
|
|
38
|
+
],
|
|
39
|
+
"author": {
|
|
40
|
+
"name": "Sv443",
|
|
41
|
+
"url": "https://github.com/Sv443"
|
|
42
|
+
},
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"bugs": {
|
|
45
|
+
"url": "https://github.com/Sv443-Network/CoreUtils/issues"
|
|
46
|
+
},
|
|
47
|
+
"homepage": "https://github.com/Sv443-Network/CoreUtils",
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"nanoevents": "^9.1.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@changesets/cli": "^2.29.4",
|
|
53
|
+
"@eslint/eslintrc": "^3.3.1",
|
|
54
|
+
"@eslint/js": "^9.26.0",
|
|
55
|
+
"@swc/core": "^1.11.29",
|
|
56
|
+
"@testing-library/dom": "^10.4.0",
|
|
57
|
+
"@types/node": "^22.15.18",
|
|
58
|
+
"@types/tx2": "^1.0.3",
|
|
59
|
+
"@typescript-eslint/eslint-plugin": "^8.32.1",
|
|
60
|
+
"@typescript-eslint/parser": "^8.32.1",
|
|
61
|
+
"@typescript-eslint/utils": "^8.32.1",
|
|
62
|
+
"@vitest/coverage-v8": "^3.1.3",
|
|
63
|
+
"esbuild-plugin-umd-wrapper": "^3.0.0",
|
|
64
|
+
"eslint": "^9.26.0",
|
|
65
|
+
"globals": "^16.1.0",
|
|
66
|
+
"jsdom": "^26.1.0",
|
|
67
|
+
"tslib": "^2.8.1",
|
|
68
|
+
"tsup": "^8.4.0",
|
|
69
|
+
"tsx": "^4.19.4",
|
|
70
|
+
"typescript": "^5.8.3",
|
|
71
|
+
"vitest": "^3.1.3"
|
|
72
|
+
},
|
|
73
|
+
"files": [
|
|
74
|
+
"/dist/CoreUtils.cjs",
|
|
75
|
+
"/dist/CoreUtils.min.cjs",
|
|
76
|
+
"/dist/CoreUtils.mjs",
|
|
77
|
+
"/dist/CoreUtils.min.mjs",
|
|
78
|
+
"/dist/CoreUtils.umd.js",
|
|
79
|
+
"/dist/CoreUtils.min.umd.js",
|
|
80
|
+
"/dist/lib/**/*.d.ts",
|
|
81
|
+
"/package.json",
|
|
82
|
+
"/README.md",
|
|
83
|
+
"/CHANGELOG.md",
|
|
84
|
+
"/LICENSE.txt"
|
|
85
|
+
]
|
|
86
|
+
}
|