@ztimson/utils 0.1.1 → 0.1.3

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.
@@ -0,0 +1,66 @@
1
+ export declare function addUnique<T>(array: T[], el: T): T[];
2
+ export declare function arrayDiff(a: any[], b: any[]): any[];
3
+ /**
4
+ * Provides a shorthand for sorting arrays of complex objects by a string property
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * let arr = [{a: 'Apple', b: 123}, {a: 'Carrot', b: 789}, {a: 'banana', b: 456}];
9
+ * arr.sort(caseInsensitiveSort('a'));
10
+ * ```
11
+ *
12
+ * @param {string} prop - Name of property to use, supports dot notation
13
+ * @returns {(a, b) => (number)} - Function to handle sort (Meant to be passed to Array.prototype.sort or used in sortFn)
14
+ */
15
+ export declare function caseInsensitiveSort(prop: string): (a: any, b: any) => number;
16
+ /**
17
+ * Recursively flatten nested arrays
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const arr = [
22
+ * {label: null, url: '/'},
23
+ * {label: 'Model Admin', url: '/model-admin'},
24
+ * [
25
+ * {label: 'Elements', url: '/model-admin/elements'},
26
+ * {label: 'Example', url: null}
27
+ * ]
28
+ * ];
29
+ *
30
+ * console.log(flattenArr(arr));
31
+ * // Output:
32
+ * [
33
+ * {label: null, url: '/'},
34
+ * {label: 'Model Admin', url: '/model-admin'},
35
+ * {label: 'Elements', url: '/model-admin/elements'},
36
+ * {label: 'Example', url: null}
37
+ * ]
38
+ * ```
39
+ *
40
+ * @param {any[]} arr - n-dimensional array
41
+ * @param {any[]} result - Internal use only -- Keeps track of recursion
42
+ * @returns {any[]} - Flattened array
43
+ */
44
+ export declare function flattenArr(arr: any[], result?: any[]): any[];
45
+ /**
46
+ * Provides a shorthand for sorting arrays of complex objects
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * let arr = [{a: {b: 2}}, {a: {b: 3}}, {a: {b: 1}}];
51
+ * arr.sort(sortByProp('a.b'));
52
+ * ```
53
+ *
54
+ * @param {string} prop - Name of property to use, supports dot notation
55
+ * @param {boolean} reverse - Reverse the order of the sort
56
+ * @returns {(a, b) => (number)} - Function to handle sort (Meant to be passed to Array.prototype.sort)
57
+ */
58
+ export declare function sortByProp(prop: string, reverse?: boolean): (a: any, b: any) => number;
59
+ export declare function findByProp(prop: string, value: any): (v: any) => boolean;
60
+ export declare function makeUnique(arr: any[]): any[];
61
+ /**
62
+ * Make sure value is an array, if it isn't wrap it in one.
63
+ * @param {T[] | T} value Value that should be an array
64
+ * @returns {T[]} Value in an array
65
+ */
66
+ export declare function makeArray<T>(value: T | T[]): T[];
@@ -0,0 +1,18 @@
1
+ export type Listener = (...args: any[]) => any;
2
+ export type TypedEvents = {
3
+ [k in string | symbol]: Listener;
4
+ } & {
5
+ '*': (event: string, ...args: any[]) => any;
6
+ };
7
+ export declare class TypedEmitter<T extends TypedEvents = TypedEvents> {
8
+ private static listeners;
9
+ private listeners;
10
+ static emit(event: any, ...args: any[]): void;
11
+ static off(event: any, listener: Listener): void;
12
+ static on(event: any, listener: Listener): () => void;
13
+ static once(event: any, listener?: Listener): Promise<any>;
14
+ emit<K extends keyof T>(event: K, ...args: Parameters<T[K]>): void;
15
+ off<K extends keyof T = string>(event: K, listener: T[K]): void;
16
+ on<K extends keyof T = string>(event: K, listener: T[K]): () => void;
17
+ once<K extends keyof T = string>(event: K, listener?: T[K]): Promise<any>;
18
+ }
@@ -0,0 +1,35 @@
1
+ export declare class CustomError extends Error {
2
+ static code: number;
3
+ private _code?;
4
+ get code(): number;
5
+ set code(c: number);
6
+ constructor(message?: string, code?: number);
7
+ static from(err: Error): CustomError;
8
+ static instanceof(err: Error): boolean;
9
+ toString(): string;
10
+ }
11
+ export declare class BadRequestError extends CustomError {
12
+ static code: number;
13
+ constructor(message?: string);
14
+ static instanceof(err: Error): boolean;
15
+ }
16
+ export declare class UnauthorizedError extends CustomError {
17
+ static code: number;
18
+ constructor(message?: string);
19
+ static instanceof(err: Error): boolean;
20
+ }
21
+ export declare class ForbiddenError extends CustomError {
22
+ static code: number;
23
+ constructor(message?: string);
24
+ static instanceof(err: Error): boolean;
25
+ }
26
+ export declare class NotFoundError extends CustomError {
27
+ static code: number;
28
+ constructor(message?: string);
29
+ static instanceof(err: Error): boolean;
30
+ }
31
+ export declare class InternalServerError extends CustomError {
32
+ static code: number;
33
+ constructor(message?: string);
34
+ static instanceof(err: Error): boolean;
35
+ }
@@ -0,0 +1,9 @@
1
+ export * from './array';
2
+ export * from './emitter';
3
+ export * from './errors';
4
+ export * from './logger';
5
+ export * from './misc';
6
+ export * from './objects';
7
+ export * from './string';
8
+ export * from './time';
9
+ export * from './xhr';
@@ -0,0 +1,65 @@
1
+ import { TypedEmitter, TypedEvents } from './emitter';
2
+ export declare const CliEffects: {
3
+ CLEAR: string;
4
+ BRIGHT: string;
5
+ DIM: string;
6
+ UNDERSCORE: string;
7
+ BLINK: string;
8
+ REVERSE: string;
9
+ HIDDEN: string;
10
+ };
11
+ export declare const CliForeground: {
12
+ BLACK: string;
13
+ RED: string;
14
+ GREEN: string;
15
+ YELLOW: string;
16
+ BLUE: string;
17
+ MAGENTA: string;
18
+ CYAN: string;
19
+ LIGHT_GREY: string;
20
+ GREY: string;
21
+ LIGHT_RED: string;
22
+ LIGHT_GREEN: string;
23
+ LIGHT_YELLOW: string;
24
+ LIGHT_BLUE: string;
25
+ LIGHT_MAGENTA: string;
26
+ LIGHT_CYAN: string;
27
+ WHITE: string;
28
+ };
29
+ export declare const CliBackground: {
30
+ BLACK: string;
31
+ RED: string;
32
+ GREEN: string;
33
+ YELLOW: string;
34
+ BLUE: string;
35
+ MAGENTA: string;
36
+ CYAN: string;
37
+ WHITE: string;
38
+ GREY: string;
39
+ };
40
+ export declare enum LOG_LEVEL {
41
+ ERROR = 0,
42
+ WARN = 1,
43
+ INFO = 2,
44
+ LOG = 3,
45
+ DEBUG = 4
46
+ }
47
+ export type LoggerEvents = TypedEvents & {
48
+ 'ERROR': (...args: any[]) => any;
49
+ 'WARN': (...args: any[]) => any;
50
+ 'INFO': (...args: any[]) => any;
51
+ 'LOG': (...args: any[]) => any;
52
+ 'DEBUG': (...args: any[]) => any;
53
+ };
54
+ export declare class Logger extends TypedEmitter<LoggerEvents> {
55
+ readonly namespace?: string | undefined;
56
+ static LOG_LEVEL: LOG_LEVEL;
57
+ constructor(namespace?: string | undefined);
58
+ private pad;
59
+ private format;
60
+ debug(...args: string[]): void;
61
+ log(...args: string[]): void;
62
+ info(...args: string[]): void;
63
+ warn(...args: string[]): void;
64
+ error(...args: string[]): void;
65
+ }
package/dist/misc.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Convert data into a form encoded format.
3
+ *
4
+ * @param {any} data - data to convert
5
+ * @returns {string} - Ecodeded form data
6
+ */
7
+ export declare function formEncode(data: any): string;
8
+ /**
9
+ * Get profile image from Gravatar
10
+ *
11
+ * @param {string} email Account email address
12
+ * @param {string} def Default image, can be a link or '404', see: https://docs.gravatar.com/general/images/
13
+ * @returns {string} Gravatar URL
14
+ */
15
+ export declare function gravatar(email: string, def?: string): string;
16
+ /** Parts of a URL */
17
+ export type ParsedUrl = {
18
+ protocol?: string;
19
+ subdomain?: string;
20
+ domain: string;
21
+ host: string;
22
+ port?: number;
23
+ path?: string;
24
+ query?: {
25
+ [name: string]: string;
26
+ };
27
+ fragment?: string;
28
+ };
29
+ /**
30
+ *
31
+ * @param {string} url
32
+ * @returns {RegExpExecArray}
33
+ */
34
+ export declare function urlParser(url: string): ParsedUrl;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Removes any null values from an object in-place
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * let test = {a: 0, b: false, c: null, d: 'abc'}
7
+ * console.log(clean(test)); // Output: {a: 0, b: false, d: 'abc'}
8
+ * ```
9
+ *
10
+ * @param {T} obj Object reference that will be cleaned
11
+ * @param undefinedOnly Ignore null values
12
+ * @returns {Partial<T>} Cleaned object
13
+ */
14
+ export declare function clean<T>(obj: T, undefinedOnly?: boolean): Partial<T>;
15
+ /**
16
+ * Create a deep copy of an object (vs. a shallow copy of references)
17
+ *
18
+ * Should be replaced by `structuredClone` once released.
19
+ *
20
+ * @param {T} value Object to copy
21
+ * @returns {T} Type
22
+ */
23
+ export declare function deepCopy<T>(value: T): T;
24
+ /**
25
+ * Get/set a property of an object using dot notation
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * // Get a value
30
+ * const name = dotNotation<string>(person, 'firstName');
31
+ * const familyCarMake = dotNotation(family, 'cars[0].make');
32
+ * // Set a value
33
+ * dotNotation(family, 'cars[0].make', 'toyota');
34
+ * ```
35
+ *
36
+ * @type T Return type
37
+ * @param {Object} obj source object to search
38
+ * @param {string} prop property name (Dot notation & indexing allowed)
39
+ * @param {any} set Set object property to value, omit to fetch value instead
40
+ * @return {T} property value
41
+ */
42
+ export declare function dotNotation<T>(obj: any, prop: string, set: T): T;
43
+ export declare function dotNotation<T>(obj: any, prop: string): T | undefined;
44
+ /**
45
+ * Recursively flatten a nested object, while maintaining key structure.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const car = {honda: {model: "Civic"}};
50
+ * console.log(flattenObj(car)); //Output {honda.model: "Civic"}
51
+ * ```
52
+ *
53
+ * @param obj - Object to flatten
54
+ * @param parent - Recursively check if key is a parent key or not
55
+ * @param result - Result
56
+ * @returns {object} - Flattened object
57
+ */
58
+ export declare function flattenObj(obj: any, parent?: any, result?: any): any;
59
+ /**
60
+ * Check that an object has the following values
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const test = {a: 2, b: 2};
65
+ * includes(test, {a: 1}); // true
66
+ * includes(test, {b: 1, c: 3}); // false
67
+ * ```
68
+ *
69
+ * @param target Object to search
70
+ * @param values Criteria to check against
71
+ * @param allowMissing Only check the keys that are available on the target
72
+ * @returns {boolean} Does target include all the values
73
+ */
74
+ export declare function includes(target: any, values: any, allowMissing?: boolean): boolean;
75
+ /**
76
+ * Deep check if two objects are equal
77
+ *
78
+ * @param {any} a - first item to compare
79
+ * @param {any} b - second item to compare
80
+ * @returns {boolean} True if they match
81
+ */
82
+ export declare function isEqual(a: any, b: any): boolean;
@@ -0,0 +1,72 @@
1
+ export declare function countChars(text: string, pattern: RegExp): number;
2
+ export declare function createHex(length: number): string;
3
+ export declare function formatPhoneNumber(number: string): string;
4
+ /**
5
+ * Insert a string into another string at a given position
6
+ *
7
+ * @example
8
+ * ```
9
+ * console.log(insertAt('Hello world!', ' glorious', 5);
10
+ * // Output: Hello glorious world!
11
+ * ```
12
+ *
13
+ * @param {string} target - Parent string you want to modify
14
+ * @param {string} str - Value that will be injected to parent
15
+ * @param {number} index - Position to inject string at
16
+ * @returns {string} - New string
17
+ */
18
+ export declare function insertAt(target: string, str: string, index: number): String;
19
+ export declare function pad(text: any, length: number, char: string, start?: boolean): any;
20
+ /**
21
+ * Generate a string of random characters.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const random = randomString();
26
+ * const randomByte = randomString(8, "01")
27
+ * ```
28
+ *
29
+ * @param {number} length - length of generated string
30
+ * @param {string} pool - character pool to generate string from
31
+ * @return {string} generated string
32
+ */
33
+ export declare function randomString(length: number, pool?: string): string;
34
+ /**
35
+ * Generate a random string with fine control over letters, numbers & symbols
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const randomLetter = randomString(1, true);
40
+ * const randomChar = randomString(1, true, true, true);
41
+ * ```
42
+ *
43
+ * @param {number} length - length of generated string
44
+ * @param {boolean} letters - Add letters to pool
45
+ * @param {boolean} numbers - Add numbers to pool
46
+ * @param {boolean} symbols - Add symbols to pool
47
+ * @return {string} generated string
48
+ */
49
+ export declare function randomStringBuilder(length: number, letters?: boolean, numbers?: boolean, symbols?: boolean): string;
50
+ /**
51
+ * Find all substrings that match a given pattern.
52
+ *
53
+ * Roughly based on `String.prototype.matchAll`.
54
+ *
55
+ * @param {string} value - String to search.
56
+ * @param {RegExp | string} regex - Regular expression to match.
57
+ * @return {RegExpExecArray[]} Found matches.
58
+ */
59
+ export declare function matchAll(value: string, regex: RegExp | string): RegExpExecArray[];
60
+ /**
61
+ * Create MD5 hash using native javascript
62
+ * @param d String to hash
63
+ * @returns {string} Hashed string
64
+ */
65
+ export declare function md5(d: string): string;
66
+ /**
67
+ * Check if email is valid
68
+ *
69
+ * @param {string} email - Target
70
+ * @returns {boolean} - Follows format
71
+ */
72
+ export declare function validateEmail(email: string): boolean;
package/dist/time.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Calculate the number of milliseconds until date/time
3
+ *
4
+ * @param {Date | number} date - Target
5
+ * @returns {number} - Number of milliseconds until target
6
+ */
7
+ export declare function timeUntil(date: Date | number): number;
8
+ /**
9
+ * Use in conjunction with `await` to pause an async script
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * async () => {
14
+ * ...
15
+ * await sleep(1000) // Pause for 1 second
16
+ * ...
17
+ * }
18
+ * ```
19
+ *
20
+ * @param {number} ms - Time to pause for in milliseconds
21
+ * @returns {Promise<unknown>} - Resolves promise when it's time to resume
22
+ */
23
+ export declare function sleep(ms: number): Promise<unknown>;
24
+ export declare function formatDate(date: Date | number | string): string;
package/dist/xhr.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { TypedEmitter, type TypedEvents } from './emitter';
2
+ export type Interceptor = (request: Response, next: () => void) => void;
3
+ export type RequestOptions = {
4
+ url?: string;
5
+ method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
6
+ body?: any;
7
+ headers?: {
8
+ [key: string | symbol]: string | null | undefined;
9
+ };
10
+ [key: string]: any;
11
+ };
12
+ export type XhrEvents = TypedEvents & {
13
+ 'REQUEST': (request: Promise<any>, options: RequestOptions) => any;
14
+ 'RESPONSE': (response: Response, options: RequestOptions) => any;
15
+ 'REJECTED': (response: Error, options: RequestOptions) => any;
16
+ };
17
+ export type XhrOptions = {
18
+ interceptors?: Interceptor[];
19
+ url?: string;
20
+ };
21
+ export declare class XHR extends TypedEmitter<XhrEvents> {
22
+ readonly opts: XhrOptions;
23
+ private static headers;
24
+ private static interceptors;
25
+ private headers;
26
+ private interceptors;
27
+ constructor(opts?: XhrOptions);
28
+ static addInterceptor(fn: Interceptor): () => void;
29
+ addInterceptor(fn: Interceptor): () => void;
30
+ request<T>(opts?: RequestOptions): Promise<T>;
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ztimson/utils",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Utility library",
5
5
  "author": "Zak Timson",
6
6
  "license": "MIT",
@@ -9,8 +9,7 @@
9
9
  "type": "git",
10
10
  "url": "https://git.zakscode.com/ztimson/js-utilities"
11
11
  },
12
- "main": "./dist/utils.cjs",
13
- "module": "./dist/utils.mjs",
12
+ "main": "./dist/utils.mjs",
14
13
  "types": "./dist/utils.d.ts",
15
14
  "scripts": {
16
15
  "build": "npx tsc && npx vite build",
package/dist/utils.d.ts DELETED
@@ -1,456 +0,0 @@
1
- declare module "objects" {
2
- /**
3
- * Removes any null values from an object in-place
4
- *
5
- * @example
6
- * ```ts
7
- * let test = {a: 0, b: false, c: null, d: 'abc'}
8
- * console.log(clean(test)); // Output: {a: 0, b: false, d: 'abc'}
9
- * ```
10
- *
11
- * @param {T} obj Object reference that will be cleaned
12
- * @param undefinedOnly Ignore null values
13
- * @returns {Partial<T>} Cleaned object
14
- */
15
- export function clean<T>(obj: T, undefinedOnly?: boolean): Partial<T>;
16
- /**
17
- * Create a deep copy of an object (vs. a shallow copy of references)
18
- *
19
- * Should be replaced by `structuredClone` once released.
20
- *
21
- * @param {T} value Object to copy
22
- * @returns {T} Type
23
- */
24
- export function deepCopy<T>(value: T): T;
25
- /**
26
- * Get/set a property of an object using dot notation
27
- *
28
- * @example
29
- * ```ts
30
- * // Get a value
31
- * const name = dotNotation<string>(person, 'firstName');
32
- * const familyCarMake = dotNotation(family, 'cars[0].make');
33
- * // Set a value
34
- * dotNotation(family, 'cars[0].make', 'toyota');
35
- * ```
36
- *
37
- * @type T Return type
38
- * @param {Object} obj source object to search
39
- * @param {string} prop property name (Dot notation & indexing allowed)
40
- * @param {any} set Set object property to value, omit to fetch value instead
41
- * @return {T} property value
42
- */
43
- export function dotNotation<T>(obj: any, prop: string, set: T): T;
44
- export function dotNotation<T>(obj: any, prop: string): T | undefined;
45
- /**
46
- * Recursively flatten a nested object, while maintaining key structure.
47
- *
48
- * @example
49
- * ```ts
50
- * const car = {honda: {model: "Civic"}};
51
- * console.log(flattenObj(car)); //Output {honda.model: "Civic"}
52
- * ```
53
- *
54
- * @param obj - Object to flatten
55
- * @param parent - Recursively check if key is a parent key or not
56
- * @param result - Result
57
- * @returns {object} - Flattened object
58
- */
59
- export function flattenObj(obj: any, parent?: any, result?: any): any;
60
- /**
61
- * Check that an object has the following values
62
- *
63
- * @example
64
- * ```ts
65
- * const test = {a: 2, b: 2};
66
- * includes(test, {a: 1}); // true
67
- * includes(test, {b: 1, c: 3}); // false
68
- * ```
69
- *
70
- * @param target Object to search
71
- * @param values Criteria to check against
72
- * @param allowMissing Only check the keys that are available on the target
73
- * @returns {boolean} Does target include all the values
74
- */
75
- export function includes(target: any, values: any, allowMissing?: boolean): boolean;
76
- /**
77
- * Deep check if two objects are equal
78
- *
79
- * @param {any} a - first item to compare
80
- * @param {any} b - second item to compare
81
- * @returns {boolean} True if they match
82
- */
83
- export function isEqual(a: any, b: any): boolean;
84
- }
85
- declare module "array" {
86
- export function addUnique<T>(array: T[], el: T): T[];
87
- export function arrayDiff(a: any[], b: any[]): any[];
88
- /**
89
- * Provides a shorthand for sorting arrays of complex objects by a string property
90
- *
91
- * @example
92
- * ```ts
93
- * let arr = [{a: 'Apple', b: 123}, {a: 'Carrot', b: 789}, {a: 'banana', b: 456}];
94
- * arr.sort(caseInsensitiveSort('a'));
95
- * ```
96
- *
97
- * @param {string} prop - Name of property to use, supports dot notation
98
- * @returns {(a, b) => (number)} - Function to handle sort (Meant to be passed to Array.prototype.sort or used in sortFn)
99
- */
100
- export function caseInsensitiveSort(prop: string): (a: any, b: any) => number;
101
- /**
102
- * Recursively flatten nested arrays
103
- *
104
- * @example
105
- * ```ts
106
- * const arr = [
107
- * {label: null, url: '/'},
108
- * {label: 'Model Admin', url: '/model-admin'},
109
- * [
110
- * {label: 'Elements', url: '/model-admin/elements'},
111
- * {label: 'Example', url: null}
112
- * ]
113
- * ];
114
- *
115
- * console.log(flattenArr(arr));
116
- * // Output:
117
- * [
118
- * {label: null, url: '/'},
119
- * {label: 'Model Admin', url: '/model-admin'},
120
- * {label: 'Elements', url: '/model-admin/elements'},
121
- * {label: 'Example', url: null}
122
- * ]
123
- * ```
124
- *
125
- * @param {any[]} arr - n-dimensional array
126
- * @param {any[]} result - Internal use only -- Keeps track of recursion
127
- * @returns {any[]} - Flattened array
128
- */
129
- export function flattenArr(arr: any[], result?: any[]): any[];
130
- /**
131
- * Provides a shorthand for sorting arrays of complex objects
132
- *
133
- * @example
134
- * ```ts
135
- * let arr = [{a: {b: 2}}, {a: {b: 3}}, {a: {b: 1}}];
136
- * arr.sort(sortByProp('a.b'));
137
- * ```
138
- *
139
- * @param {string} prop - Name of property to use, supports dot notation
140
- * @param {boolean} reverse - Reverse the order of the sort
141
- * @returns {(a, b) => (number)} - Function to handle sort (Meant to be passed to Array.prototype.sort)
142
- */
143
- export function sortByProp(prop: string, reverse?: boolean): (a: any, b: any) => number;
144
- export function findByProp(prop: string, value: any): (v: any) => boolean;
145
- export function makeUnique(arr: any[]): any[];
146
- /**
147
- * Make sure value is an array, if it isn't wrap it in one.
148
- * @param {T[] | T} value Value that should be an array
149
- * @returns {T[]} Value in an array
150
- */
151
- export function makeArray<T>(value: T | T[]): T[];
152
- }
153
- declare module "emitter" {
154
- export type Listener = (...args: any[]) => any;
155
- export type TypedEvents = {
156
- [k in string | symbol]: Listener;
157
- } & {
158
- '*': (event: string, ...args: any[]) => any;
159
- };
160
- export class TypedEmitter<T extends TypedEvents = TypedEvents> {
161
- private static listeners;
162
- private listeners;
163
- static emit(event: any, ...args: any[]): void;
164
- static off(event: any, listener: Listener): void;
165
- static on(event: any, listener: Listener): () => void;
166
- static once(event: any, listener?: Listener): Promise<any>;
167
- emit<K extends keyof T>(event: K, ...args: Parameters<T[K]>): void;
168
- off<K extends keyof T = string>(event: K, listener: T[K]): void;
169
- on<K extends keyof T = string>(event: K, listener: T[K]): () => void;
170
- once<K extends keyof T = string>(event: K, listener?: T[K]): Promise<any>;
171
- }
172
- }
173
- declare module "xhr" {
174
- import { TypedEmitter, type TypedEvents } from "emitter";
175
- export type Interceptor = (request: Response, next: () => void) => void;
176
- export type RequestOptions = {
177
- url?: string;
178
- method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
179
- body?: any;
180
- headers?: {
181
- [key: string | symbol]: string | null | undefined;
182
- };
183
- [key: string]: any;
184
- };
185
- export type XhrEvents = TypedEvents & {
186
- 'REQUEST': (request: Promise<any>, options: RequestOptions) => any;
187
- 'RESPONSE': (response: Response, options: RequestOptions) => any;
188
- 'REJECTED': (response: Error, options: RequestOptions) => any;
189
- };
190
- export type XhrOptions = {
191
- interceptors?: Interceptor[];
192
- url?: string;
193
- };
194
- export class XHR extends TypedEmitter<XhrEvents> {
195
- readonly opts: XhrOptions;
196
- private static headers;
197
- private static interceptors;
198
- private headers;
199
- private interceptors;
200
- constructor(opts?: XhrOptions);
201
- static addInterceptor(fn: Interceptor): () => void;
202
- addInterceptor(fn: Interceptor): () => void;
203
- request<T>(opts?: RequestOptions): Promise<T>;
204
- }
205
- }
206
- declare module "errors" {
207
- export class CustomError extends Error {
208
- static code: number;
209
- private _code?;
210
- get code(): number;
211
- set code(c: number);
212
- constructor(message?: string, code?: number);
213
- static from(err: Error): CustomError;
214
- static instanceof(err: Error): boolean;
215
- toString(): string;
216
- }
217
- export class BadRequestError extends CustomError {
218
- static code: number;
219
- constructor(message?: string);
220
- static instanceof(err: Error): boolean;
221
- }
222
- export class UnauthorizedError extends CustomError {
223
- static code: number;
224
- constructor(message?: string);
225
- static instanceof(err: Error): boolean;
226
- }
227
- export class ForbiddenError extends CustomError {
228
- static code: number;
229
- constructor(message?: string);
230
- static instanceof(err: Error): boolean;
231
- }
232
- export class NotFoundError extends CustomError {
233
- static code: number;
234
- constructor(message?: string);
235
- static instanceof(err: Error): boolean;
236
- }
237
- export class InternalServerError extends CustomError {
238
- static code: number;
239
- constructor(message?: string);
240
- static instanceof(err: Error): boolean;
241
- }
242
- }
243
- declare module "logger" {
244
- import { TypedEmitter, TypedEvents } from "emitter";
245
- export const CliEffects: {
246
- CLEAR: string;
247
- BRIGHT: string;
248
- DIM: string;
249
- UNDERSCORE: string;
250
- BLINK: string;
251
- REVERSE: string;
252
- HIDDEN: string;
253
- };
254
- export const CliForeground: {
255
- BLACK: string;
256
- RED: string;
257
- GREEN: string;
258
- YELLOW: string;
259
- BLUE: string;
260
- MAGENTA: string;
261
- CYAN: string;
262
- LIGHT_GREY: string;
263
- GREY: string;
264
- LIGHT_RED: string;
265
- LIGHT_GREEN: string;
266
- LIGHT_YELLOW: string;
267
- LIGHT_BLUE: string;
268
- LIGHT_MAGENTA: string;
269
- LIGHT_CYAN: string;
270
- WHITE: string;
271
- };
272
- export const CliBackground: {
273
- BLACK: string;
274
- RED: string;
275
- GREEN: string;
276
- YELLOW: string;
277
- BLUE: string;
278
- MAGENTA: string;
279
- CYAN: string;
280
- WHITE: string;
281
- GREY: string;
282
- };
283
- export enum LOG_LEVEL {
284
- ERROR = 0,
285
- WARN = 1,
286
- INFO = 2,
287
- LOG = 3,
288
- DEBUG = 4
289
- }
290
- export type LoggerEvents = TypedEvents & {
291
- 'ERROR': (...args: any[]) => any;
292
- 'WARN': (...args: any[]) => any;
293
- 'INFO': (...args: any[]) => any;
294
- 'LOG': (...args: any[]) => any;
295
- 'DEBUG': (...args: any[]) => any;
296
- };
297
- export class Logger extends TypedEmitter<LoggerEvents> {
298
- readonly namespace?: string | undefined;
299
- static LOG_LEVEL: LOG_LEVEL;
300
- constructor(namespace?: string | undefined);
301
- private pad;
302
- private format;
303
- debug(...args: string[]): void;
304
- log(...args: string[]): void;
305
- info(...args: string[]): void;
306
- warn(...args: string[]): void;
307
- error(...args: string[]): void;
308
- }
309
- }
310
- declare module "string" {
311
- export function countChars(text: string, pattern: RegExp): number;
312
- export function createHex(length: number): string;
313
- export function formatPhoneNumber(number: string): string;
314
- /**
315
- * Insert a string into another string at a given position
316
- *
317
- * @example
318
- * ```
319
- * console.log(insertAt('Hello world!', ' glorious', 5);
320
- * // Output: Hello glorious world!
321
- * ```
322
- *
323
- * @param {string} target - Parent string you want to modify
324
- * @param {string} str - Value that will be injected to parent
325
- * @param {number} index - Position to inject string at
326
- * @returns {string} - New string
327
- */
328
- export function insertAt(target: string, str: string, index: number): String;
329
- export function pad(text: any, length: number, char: string, start?: boolean): any;
330
- /**
331
- * Generate a string of random characters.
332
- *
333
- * @example
334
- * ```ts
335
- * const random = randomString();
336
- * const randomByte = randomString(8, "01")
337
- * ```
338
- *
339
- * @param {number} length - length of generated string
340
- * @param {string} pool - character pool to generate string from
341
- * @return {string} generated string
342
- */
343
- export function randomString(length: number, pool?: string): string;
344
- /**
345
- * Generate a random string with fine control over letters, numbers & symbols
346
- *
347
- * @example
348
- * ```ts
349
- * const randomLetter = randomString(1, true);
350
- * const randomChar = randomString(1, true, true, true);
351
- * ```
352
- *
353
- * @param {number} length - length of generated string
354
- * @param {boolean} letters - Add letters to pool
355
- * @param {boolean} numbers - Add numbers to pool
356
- * @param {boolean} symbols - Add symbols to pool
357
- * @return {string} generated string
358
- */
359
- export function randomStringBuilder(length: number, letters?: boolean, numbers?: boolean, symbols?: boolean): string;
360
- /**
361
- * Find all substrings that match a given pattern.
362
- *
363
- * Roughly based on `String.prototype.matchAll`.
364
- *
365
- * @param {string} value - String to search.
366
- * @param {RegExp | string} regex - Regular expression to match.
367
- * @return {RegExpExecArray[]} Found matches.
368
- */
369
- export function matchAll(value: string, regex: RegExp | string): RegExpExecArray[];
370
- /**
371
- * Create MD5 hash using native javascript
372
- * @param d String to hash
373
- * @returns {string} Hashed string
374
- */
375
- export function md5(d: string): string;
376
- /**
377
- * Check if email is valid
378
- *
379
- * @param {string} email - Target
380
- * @returns {boolean} - Follows format
381
- */
382
- export function validateEmail(email: string): boolean;
383
- }
384
- declare module "misc" {
385
- /**
386
- * Convert data into a form encoded format.
387
- *
388
- * @param {any} data - data to convert
389
- * @returns {string} - Ecodeded form data
390
- */
391
- export function formEncode(data: any): string;
392
- /**
393
- * Get profile image from Gravatar
394
- *
395
- * @param {string} email Account email address
396
- * @param {string} def Default image, can be a link or '404', see: https://docs.gravatar.com/general/images/
397
- * @returns {string} Gravatar URL
398
- */
399
- export function gravatar(email: string, def?: string): string;
400
- /** Parts of a URL */
401
- export type ParsedUrl = {
402
- protocol?: string;
403
- subdomain?: string;
404
- domain: string;
405
- host: string;
406
- port?: number;
407
- path?: string;
408
- query?: {
409
- [name: string]: string;
410
- };
411
- fragment?: string;
412
- };
413
- /**
414
- *
415
- * @param {string} url
416
- * @returns {RegExpExecArray}
417
- */
418
- export function urlParser(url: string): ParsedUrl;
419
- }
420
- declare module "time" {
421
- /**
422
- * Calculate the number of milliseconds until date/time
423
- *
424
- * @param {Date | number} date - Target
425
- * @returns {number} - Number of milliseconds until target
426
- */
427
- export function timeUntil(date: Date | number): number;
428
- /**
429
- * Use in conjunction with `await` to pause an async script
430
- *
431
- * @example
432
- * ```ts
433
- * async () => {
434
- * ...
435
- * await sleep(1000) // Pause for 1 second
436
- * ...
437
- * }
438
- * ```
439
- *
440
- * @param {number} ms - Time to pause for in milliseconds
441
- * @returns {Promise<unknown>} - Resolves promise when it's time to resume
442
- */
443
- export function sleep(ms: number): Promise<unknown>;
444
- export function formatDate(date: Date | number | string): string;
445
- }
446
- declare module "index" {
447
- export * from "array";
448
- export * from "emitter";
449
- export * from "errors";
450
- export * from "logger";
451
- export * from "misc";
452
- export * from "objects";
453
- export * from "string";
454
- export * from "time";
455
- export * from "xhr";
456
- }