@catbee/utils 2.0.0-next.0 → 2.0.0-next.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.
Files changed (97) hide show
  1. package/README.md +52 -16
  2. package/array/index.cjs +180 -71
  3. package/array/index.d.ts +293 -1
  4. package/array/index.mjs +171 -72
  5. package/async/index.cjs +92 -36
  6. package/async/index.d.ts +275 -1
  7. package/async/index.mjs +92 -36
  8. package/cache/index.cjs +1 -1
  9. package/cache/index.d.ts +155 -1
  10. package/cache/index.mjs +2 -2
  11. package/config/index.cjs +78 -64
  12. package/config/index.d.ts +64 -2
  13. package/config/index.mjs +76 -64
  14. package/context-store/index.d.ts +192 -1
  15. package/crypto/index.d.ts +163 -1
  16. package/date/index.cjs +46 -1
  17. package/date/index.d.ts +190 -1
  18. package/date/index.mjs +45 -2
  19. package/decorators/index.cjs +1156 -18
  20. package/decorators/index.d.ts +684 -1
  21. package/decorators/index.mjs +1156 -18
  22. package/dir/index.cjs +4 -3
  23. package/dir/index.d.ts +195 -1
  24. package/dir/index.mjs +4 -3
  25. package/env/index.cjs +10 -26
  26. package/env/index.d.ts +379 -1
  27. package/env/index.mjs +10 -26
  28. package/exception/index.d.ts +232 -1
  29. package/fs/index.cjs +70 -36
  30. package/fs/index.d.ts +205 -1
  31. package/fs/index.mjs +64 -34
  32. package/http-status-codes/index.d.ts +267 -1
  33. package/id/index.d.ts +37 -1
  34. package/index.cjs +3 -3
  35. package/index.d.ts +1 -1
  36. package/index.mjs +1 -1
  37. package/logger/index.cjs +11 -11
  38. package/logger/index.d.ts +189 -1
  39. package/logger/index.mjs +12 -12
  40. package/middleware/index.d.ts +103 -1
  41. package/obj/index.cjs +150 -162
  42. package/obj/index.d.ts +136 -1
  43. package/obj/index.mjs +150 -162
  44. package/package.json +11 -11
  45. package/performance/index.cjs +2 -2
  46. package/performance/index.d.ts +138 -1
  47. package/performance/index.mjs +2 -2
  48. package/request/index.cjs +1 -1
  49. package/request/index.d.ts +241 -2
  50. package/request/index.mjs +1 -1
  51. package/response/index.d.ts +318 -2
  52. package/server/index.cjs +27 -23
  53. package/server/index.d.ts +785 -4
  54. package/server/index.mjs +28 -23
  55. package/stream/index.d.ts +90 -1
  56. package/string/index.d.ts +102 -1
  57. package/type/index.cjs +1 -1
  58. package/type/index.d.ts +107 -1
  59. package/type/index.mjs +1 -1
  60. package/types/index.d.ts +774 -4
  61. package/url/index.cjs +2 -4
  62. package/url/index.d.ts +142 -1
  63. package/url/index.mjs +2 -4
  64. package/{validate → validation}/index.cjs +89 -42
  65. package/{validate/validate.utils.d.ts → validation/index.d.ts} +32 -23
  66. package/{validate → validation}/index.mjs +85 -42
  67. package/array/array.utils.d.ts +0 -191
  68. package/async/async.utils.d.ts +0 -296
  69. package/cache/cache.utils.d.ts +0 -176
  70. package/config/config.d.ts +0 -57
  71. package/context-store/context-store.utils.d.ts +0 -212
  72. package/crypto/crypto.utils.d.ts +0 -183
  73. package/date/date.utils.d.ts +0 -190
  74. package/decorators/decorators.utils.d.ts +0 -705
  75. package/dir/dir.utils.d.ts +0 -216
  76. package/env/env.utils.d.ts +0 -400
  77. package/exception/exception.utils.d.ts +0 -253
  78. package/fs/fs.utils.d.ts +0 -196
  79. package/http-status-codes/http-status-codes.d.ts +0 -289
  80. package/id/id.utils.d.ts +0 -59
  81. package/logger/logger.utils.d.ts +0 -210
  82. package/middleware/middleware.utils.d.ts +0 -123
  83. package/obj/obj.utils.d.ts +0 -156
  84. package/performance/performance.utils.d.ts +0 -159
  85. package/request/request.utils.d.ts +0 -109
  86. package/response/response.utils.d.ts +0 -186
  87. package/server/server.builder.d.ts +0 -531
  88. package/server/server.d.ts +0 -303
  89. package/stream/stream.utils.d.ts +0 -111
  90. package/string/string.utils.d.ts +0 -124
  91. package/type/type.utils.d.ts +0 -129
  92. package/types/api-response.d.ts +0 -175
  93. package/types/common.d.ts +0 -148
  94. package/types/config.d.ts +0 -88
  95. package/types/server.d.ts +0 -291
  96. package/url/url.utils.d.ts +0 -164
  97. package/validate/index.d.ts +0 -25
@@ -1,212 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
-
25
- import { AsyncLocalStorage } from 'async_hooks';
26
- /**
27
- * Type representing the store object used in AsyncLocalStorage.
28
- * Keys must be unique symbols to ensure isolation and prevent collisions.
29
- */
30
- export interface Store {
31
- [key: symbol]: unknown;
32
- }
33
- /**
34
- * Predefined symbols used as keys in AsyncLocalStorage.
35
- * Add new symbols here to avoid duplication.
36
- */
37
- export declare const StoreKeys: {
38
- LOGGER: symbol;
39
- REQUEST_ID: symbol;
40
- USER: symbol;
41
- SESSION: symbol;
42
- TRANSACTION_ID: symbol;
43
- USER_ID: symbol;
44
- TENANT_ID: symbol;
45
- TRACE_ID: symbol;
46
- CORRELATION_ID: symbol;
47
- };
48
- /**
49
- * Retrieves the current request ID from the async context, if available.
50
- *
51
- * @returns {string | undefined} The request ID string or undefined if not present in the current context.
52
- */
53
- export declare function getRequestId(): string | undefined;
54
- /**
55
- * Type-safe getter for common context values.
56
- *
57
- * @param key The store key symbol
58
- * @returns The typed value from the store
59
- */
60
- export declare function getFromContext<T>(key: symbol): T | undefined;
61
- /**
62
- * ContextStore manages per-request scoped context using AsyncLocalStorage.
63
- * It allows storing and retrieving data across async calls (e.g., request ID, logger).
64
- *
65
- * Example (Express middleware):
66
- * ```
67
- * // Middleware to initialize context and logger
68
- * app.use((req, res, next) => {
69
- * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
70
- * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
71
- * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
72
- * next();
73
- * });
74
- * });
75
- * ```
76
- */
77
- export declare class ContextStore {
78
- /**
79
- * The underlying AsyncLocalStorage instance for context.
80
- * @private
81
- */
82
- private static readonly storage;
83
- /**
84
- * Returns the raw AsyncLocalStorage instance for advanced access.
85
- *
86
- * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
87
- */
88
- static getInstance(): AsyncLocalStorage<Store>;
89
- /**
90
- * Retrieves a value from the async context store by symbol key.
91
- *
92
- * @typeParam T - The expected return type of the value.
93
- * @param {symbol} key - Unique symbol used as the store key.
94
- * @returns {T | undefined} The value found (typed) or undefined if not present.
95
- */
96
- static get<T>(key: symbol): T | undefined;
97
- /**
98
- * Sets a value in the current context store by symbol key.
99
- *
100
- * @typeParam T - The value type to set.
101
- * @param {symbol} key - Unique symbol key.
102
- * @param {T} value - Value to set in context.
103
- * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
104
- */
105
- static set<T>(key: symbol, value: T): void;
106
- /**
107
- * Retrieves the entire context store object for the current async context.
108
- *
109
- * @returns {Store | undefined} The current store object or undefined if called outside a context.
110
- */
111
- static getAll(): Store | undefined;
112
- /**
113
- * Initializes a new async context and executes a callback within it.
114
- * This must be called at the beginning of a request or logical async flow.
115
- *
116
- * @typeParam T - The callback's return type.
117
- * @param {Store} store - The initial key-value store object.
118
- * @param {() => T} callback - The function to run within the new context.
119
- * @returns {T} The result of the callback function.
120
- */
121
- static run<T>(store: Store, callback: () => T): T;
122
- /**
123
- * Checks if a key exists in the current context store.
124
- *
125
- * @param {symbol} key - The symbol key to check.
126
- * @returns {boolean} True if the key exists, false otherwise.
127
- */
128
- static has(key: symbol): boolean;
129
- /**
130
- * Removes a value from the current context store by symbol key.
131
- *
132
- * @param {symbol} key - The symbol key to delete.
133
- * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
134
- * @throws {Error} If called outside an active context.
135
- */
136
- static delete(key: symbol): boolean;
137
- /**
138
- * Updates multiple values in the current context store at once.
139
- *
140
- * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
141
- * @throws {Error} If called outside an active context.
142
- */
143
- static patch(values: Partial<Record<symbol, unknown>>): void;
144
- /**
145
- * Executes a callback with a temporary store value that only exists during execution.
146
- * Original store is restored after callback completes.
147
- *
148
- * @typeParam T - The callback's return type.
149
- * @param {symbol} key - The symbol key to temporarily set.
150
- * @param {unknown} value - The temporary value.
151
- * @param {() => T} callback - The function to execute with the temporary value.
152
- * @returns {T} The result of the callback function.
153
- * @throws {Error} If called outside an active context.
154
- */
155
- static withValue<T>(key: symbol, value: unknown, callback: () => T): T;
156
- /**
157
- * Creates a new context that inherits values from the current context.
158
- *
159
- * @typeParam T - The callback's return type.
160
- * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
161
- * @param {() => T} callback - The function to execute in the new context.
162
- * @returns {T} The result of the callback function.
163
- */
164
- static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T;
165
- /**
166
- * Creates Express middleware that initializes a context for each request.
167
- *
168
- * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
169
- * @returns Express middleware function.
170
- */
171
- static createExpressMiddleware(initialValuesFactory?: (req: any) => Partial<Record<symbol, unknown>>): (req: any, _res: any, next: any) => void;
172
- }
173
- /**
174
- * Type-safe wrapper for accessing and modifying context values with specific types.
175
- *
176
- * @typeParam T - The value type.
177
- */
178
- export declare class TypedContextKey<T> {
179
- private symbol;
180
- private defaultValue?;
181
- /**
182
- * Creates a new typed context key.
183
- *
184
- * @param symbol - The unique symbol for this key
185
- * @param defaultValue - Optional default value if key is not found
186
- */
187
- constructor(symbol: symbol, defaultValue?: T | undefined);
188
- /**
189
- * Gets the current value for this key.
190
- *
191
- * @returns The value or defaultValue if not found
192
- */
193
- get(): T | undefined;
194
- /**
195
- * Sets the value for this key.
196
- *
197
- * @param value The value to set
198
- */
199
- set(value: T): void;
200
- /**
201
- * Checks if this key exists in the context.
202
- *
203
- * @returns True if the key exists
204
- */
205
- exists(): boolean;
206
- /**
207
- * Deletes this key from the context.
208
- *
209
- * @returns True if the key was deleted
210
- */
211
- delete(): boolean;
212
- }
@@ -1,183 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
-
25
- import { BinaryToTextEncoding, CipherGCMTypes } from 'crypto';
26
- export type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
27
- /**
28
- * Generates an HMAC digest using the specified algorithm and secret key.
29
- *
30
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
31
- * @param {string} input - The string to hash.
32
- * @param {string} secret - The secret key for HMAC.
33
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
34
- * @returns {string} HMAC digest as a string.
35
- */
36
- export declare function hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string;
37
- /**
38
- * Generates a hash digest using the specified algorithm.
39
- *
40
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
41
- * @param {string} input - The string to hash.
42
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
43
- * @returns {string} Hash digest as a string.
44
- */
45
- export declare function hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string;
46
- /**
47
- * Generates an HMAC-SHA256 digest.
48
- *
49
- * @param {string} input - The string to hash.
50
- * @param {string} secret - The secret key.
51
- * @returns {string} SHA-256 HMAC digest as a string.
52
- */
53
- export declare function sha256Hmac(input: string, secret: string): string;
54
- /**
55
- * Generates a SHA1 hash digest.
56
- *
57
- * @param {string} input - The string to hash.
58
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
59
- * @returns {string} SHA-1 hash as a string.
60
- */
61
- export declare function sha1(input: string, encoding?: BinaryToTextEncoding): string;
62
- /**
63
- * Generates a SHA256 hash digest.
64
- *
65
- * @param {string} input - The string to hash.
66
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
67
- * @returns {string} SHA-256 hash as a string.
68
- */
69
- export declare function sha256(input: string, encoding?: BinaryToTextEncoding): string;
70
- /**
71
- * Generates an MD5 hash digest.
72
- *
73
- * @param {string} input - The string to hash.
74
- * @returns {string} MD5 hash as a string.
75
- */
76
- export declare function md5(input: string): string;
77
- /**
78
- * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
79
- *
80
- * @returns {string} Random string hashed with SHA-256 (hex encoding).
81
- */
82
- export declare function randomString(): string;
83
- /**
84
- * Generates a secure random buffer of specified byte length.
85
- *
86
- * @param {number} [byteLength=32] - Number of random bytes to generate.
87
- * @returns {Buffer} Buffer containing random bytes.
88
- */
89
- export declare function generateRandomBytes(byteLength?: number): Buffer;
90
- /**
91
- * Generates a secure random string of specified byte length with specified encoding.
92
- *
93
- * @param {number} [byteLength=32] - Number of random bytes to generate.
94
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
95
- * @returns {string} Random string in specified encoding.
96
- */
97
- export declare function generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string;
98
- /**
99
- * Generates a secure API key with a specified format.
100
- *
101
- * @param {string} [prefix=''] - Optional prefix for the key.
102
- * @param {number} [byteLength=24] - Number of random bytes to generate.
103
- * @returns {string} Formatted API key.
104
- */
105
- export declare function generateApiKey(prefix?: string, byteLength?: number): string;
106
- /**
107
- * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
108
- *
109
- * @param {string | Buffer | Uint8Array} a - First value to compare
110
- * @param {string | Buffer | Uint8Array} b - Second value to compare
111
- * @returns {boolean} True if values are equal
112
- */
113
- export declare function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
114
- /**
115
- * Interface for encryption options
116
- */
117
- export interface EncryptionOptions {
118
- /** Algorithm to use (default: aes-256-gcm) */
119
- algorithm?: CipherGCMTypes;
120
- /** Input encoding for plaintext if string (default: utf8) */
121
- inputEncoding?: BufferEncoding;
122
- /** Output encoding for ciphertext (default: hex) */
123
- outputEncoding?: BinaryToTextEncoding;
124
- }
125
- /**
126
- * Interface for decryption options
127
- */
128
- export interface DecryptionOptions {
129
- /** Algorithm to use (default: aes-256-gcm) */
130
- algorithm?: CipherGCMTypes;
131
- /** Input encoding for ciphertext if string (default: hex) */
132
- inputEncoding?: BinaryToTextEncoding;
133
- /** Output encoding for plaintext (default: utf8) */
134
- outputEncoding?: BufferEncoding;
135
- }
136
- /**
137
- * Result of encryption operation including all data needed for decryption
138
- */
139
- export interface EncryptionResult {
140
- /** Encrypted data (string or Buffer based on options) */
141
- ciphertext: string | Buffer;
142
- /** Initialization vector */
143
- iv: Buffer;
144
- /** Authentication tag (for GCM mode) */
145
- authTag?: Buffer;
146
- /** Algorithm used */
147
- algorithm: string;
148
- }
149
- /**
150
- * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
151
- *
152
- * @param {string | Buffer} data - Data to encrypt
153
- * @param {string | Buffer} key - Encryption key or passphrase
154
- * @param {EncryptionOptions} [options] - Encryption options
155
- * @returns {Promise<EncryptionResult>} Encrypted data with metadata
156
- */
157
- export declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>;
158
- /**
159
- * Decrypts data that was encrypted with the encrypt function.
160
- *
161
- * @param {EncryptionResult} encryptedData - The encrypted data and metadata
162
- * @param {string | Buffer} key - Decryption key or passphrase
163
- * @param {DecryptionOptions} [options] - Decryption options
164
- * @returns {Promise<string | Buffer>} Decrypted data
165
- */
166
- export declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>;
167
- /**
168
- * Creates a signed token with an expiration time and payload.
169
- *
170
- * @param {object} payload - Data to include in the token
171
- * @param {string} secret - Secret key for signing
172
- * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
173
- * @returns {string} Signed token string
174
- */
175
- export declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string;
176
- /**
177
- * Verifies and decodes a signed token.
178
- *
179
- * @param {string} token - The token to verify
180
- * @param {string} secret - Secret key for verification
181
- * @returns {object | null} Decoded payload if valid, null if invalid
182
- */
183
- export declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;
@@ -1,190 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
-
25
- /**
26
- * Format options for the formatDate function
27
- */
28
- export interface DateFormatOptions {
29
- /** Date format pattern (default: 'yyyy-MM-dd') */
30
- format?: string;
31
- /** Locale to use for formatting (default: system locale) */
32
- locale?: string | string[];
33
- /** Time zone to use (default: system time zone) */
34
- timeZone?: string;
35
- }
36
- /**
37
- * Format a date according to the specified format pattern.
38
- *
39
- * @param date - Date to format
40
- * @param options - Formatting options
41
- * @returns Formatted date string
42
- *
43
- * @example
44
- * ```typescript
45
- * // Format as ISO date
46
- * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'
47
- *
48
- * // Format with time
49
- * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'
50
- *
51
- * // Format with locale
52
- * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'
53
- * ```
54
- */
55
- export declare function formatDate(date: Date | number, options?: DateFormatOptions): string;
56
- /**
57
- * Format a date as relative time (e.g., "5 minutes ago", "in 3 days").
58
- *
59
- * @param date - Date to format
60
- * @param now - Reference date (default: current time)
61
- * @param locale - Locale to use for formatting
62
- * @returns Formatted relative time string
63
- */
64
- export declare function formatRelativeTime(date: Date | number, now?: Date | number, locale?: string | string[]): string;
65
- /**
66
- * Parse a date string or timestamp into a Date object.
67
- *
68
- * @param input - Date string or timestamp to parse
69
- * @param fallback - Fallback date if parsing fails
70
- * @returns Parsed Date object or fallback
71
- *
72
- * @example
73
- * ```typescript
74
- * parseDate('2023-05-15'); // Date object for May 15, 2023
75
- * parseDate('invalid', new Date()); // Returns current date as fallback
76
- * ```
77
- */
78
- export declare function parseDate(input: string | number, fallback?: Date): Date | null;
79
- /**
80
- * Calculate the difference between two dates in the specified unit.
81
- *
82
- * @param date1 - First date
83
- * @param date2 - Second date (default: current time)
84
- * @param unit - Unit of time for the difference
85
- * @returns Difference in the specified unit
86
- *
87
- * @example
88
- * ```typescript
89
- * // Get difference in days
90
- * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5
91
- *
92
- * // Get difference in hours
93
- * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4
94
- * ```
95
- */
96
- export declare function dateDiff(date1: Date | number, date2?: Date | number, unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number;
97
- /**
98
- * Add a specified amount of time to a date.
99
- *
100
- * @param date - Base date
101
- * @param amount - Amount to add (can be negative)
102
- * @param unit - Unit of time to add
103
- * @returns New date with the addition
104
- *
105
- * @example
106
- * ```typescript
107
- * // Add 5 days
108
- * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023
109
- *
110
- * // Subtract 2 hours
111
- * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00
112
- * ```
113
- */
114
- export declare function addToDate(date: Date | number, amount: number, unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): Date;
115
- /**
116
- * Get the start of a time period containing the specified date.
117
- *
118
- * @param date - Date to get the start from
119
- * @param unit - Time unit
120
- * @returns Date object representing the start of the time unit
121
- *
122
- * @example
123
- * ```typescript
124
- * // Get start of day (midnight)
125
- * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00
126
- *
127
- * // Get start of month
128
- * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023
129
- * ```
130
- */
131
- export declare function startOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
132
- /**
133
- * Get the end of a time period containing the specified date.
134
- *
135
- * @param date - Date to get the end from
136
- * @param unit - Time unit
137
- * @returns Date object representing the end of the time unit
138
- *
139
- * @example
140
- * ```typescript
141
- * // Get end of day (23:59:59.999)
142
- * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999
143
- *
144
- * // Get end of month
145
- * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999
146
- * ```
147
- */
148
- export declare function endOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
149
- /**
150
- * Check if a date is between two other dates.
151
- *
152
- * @param date - Date to check
153
- * @param start - Start date of the range
154
- * @param end - End date of the range
155
- * @param inclusive - Whether the comparison should be inclusive of start/end
156
- * @returns True if the date is within the range
157
- *
158
- * @example
159
- * ```typescript
160
- * const date = new Date('2023-05-15');
161
- * const start = new Date('2023-05-10');
162
- * const end = new Date('2023-05-20');
163
- *
164
- * isBetween(date, start, end); // true
165
- * ```
166
- */
167
- export declare function isBetween(date: Date | number, start: Date | number, end: Date | number, inclusive?: boolean): boolean;
168
- /**
169
- * Check if a year is a leap year.
170
- *
171
- * @param year - Year to check (or date object)
172
- * @returns True if the year is a leap year
173
- */
174
- export declare function isLeapYear(year: number | Date): boolean;
175
- /**
176
- * Get the number of days in a month.
177
- *
178
- * @param year - Year
179
- * @param month - Month (0-11)
180
- * @returns Number of days in the month
181
- */
182
- export declare function daysInMonth(year: number | Date, month?: number): number;
183
- /**
184
- * Format a duration given in milliseconds to a human readable string.
185
- * Examples: 3661000 -> "1h 1m 1s", 90061 -> "1m 30s 61ms"
186
- *
187
- * @param {number} ms - Duration in milliseconds
188
- * @returns {string} Human readable duration
189
- */
190
- export declare function formatDuration(ms: number): string;