@naman_deep_singh/utils 2.3.0 → 2.6.0

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 (58) hide show
  1. package/README.md +228 -129
  2. package/dist/cjs/array/arrayExtensions.js +23 -23
  3. package/dist/cjs/core/index.js +14 -16
  4. package/dist/cjs/errors/CompressionError.js +19 -0
  5. package/dist/cjs/errors/ConnectionError.js +21 -0
  6. package/dist/cjs/errors/PoolError.js +20 -0
  7. package/dist/cjs/errors/TimeoutError.js +24 -0
  8. package/dist/cjs/errors/ValidationError.js +22 -0
  9. package/dist/cjs/errors/index.js +13 -0
  10. package/dist/cjs/extensions/index.js +9 -18
  11. package/dist/cjs/init/index.js +7 -16
  12. package/dist/cjs/init/initializer.js +10 -10
  13. package/dist/cjs/number/numberExtensions.js +23 -23
  14. package/dist/cjs/object/objectExtensions.js +14 -14
  15. package/dist/cjs/string/stringExtensions.js +22 -22
  16. package/dist/cjs/types/index.js +0 -17
  17. package/dist/cjs/utils/compression.js +455 -0
  18. package/dist/cjs/utils/index.js +35 -18
  19. package/dist/cjs/utils/pool.js +375 -0
  20. package/dist/cjs/utils/timeout.js +133 -0
  21. package/dist/esm/array/arrayExtensions.js +1 -1
  22. package/dist/esm/core/index.js +3 -2
  23. package/dist/esm/errors/CompressionError.js +15 -0
  24. package/dist/esm/errors/ConnectionError.js +17 -0
  25. package/dist/esm/errors/PoolError.js +16 -0
  26. package/dist/esm/errors/TimeoutError.js +20 -0
  27. package/dist/esm/errors/ValidationError.js +18 -0
  28. package/dist/esm/errors/index.js +5 -0
  29. package/dist/esm/extensions/index.js +4 -4
  30. package/dist/esm/init/index.js +2 -2
  31. package/dist/esm/init/initializer.js +5 -5
  32. package/dist/esm/number/numberExtensions.js +2 -2
  33. package/dist/esm/object/objectExtensions.js +1 -1
  34. package/dist/esm/string/stringExtensions.js +1 -1
  35. package/dist/esm/types/index.js +1 -3
  36. package/dist/esm/utils/compression.js +415 -0
  37. package/dist/esm/utils/index.js +16 -4
  38. package/dist/esm/utils/pool.js +370 -0
  39. package/dist/esm/utils/timeout.js +128 -0
  40. package/dist/types/core/index.d.ts +3 -2
  41. package/dist/types/errors/CompressionError.d.ts +8 -0
  42. package/dist/types/errors/ConnectionError.d.ts +9 -0
  43. package/dist/types/errors/PoolError.d.ts +8 -0
  44. package/dist/types/errors/TimeoutError.d.ts +12 -0
  45. package/dist/types/errors/ValidationError.d.ts +9 -0
  46. package/dist/types/errors/index.d.ts +5 -0
  47. package/dist/types/extensions/index.d.ts +4 -4
  48. package/dist/types/init/index.d.ts +2 -2
  49. package/dist/types/init/initializer.d.ts +1 -1
  50. package/dist/types/init/options.d.ts +1 -1
  51. package/dist/types/types/extensionTypes.d.ts +1 -1
  52. package/dist/types/types/index.d.ts +1 -2
  53. package/dist/types/utils/compression.d.ts +164 -0
  54. package/dist/types/utils/config.d.ts +1 -1
  55. package/dist/types/utils/index.d.ts +11 -3
  56. package/dist/types/utils/pool.d.ts +157 -0
  57. package/dist/types/utils/timeout.d.ts +64 -0
  58. package/package.json +2 -1
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Compression utilities for data compression/decompression
3
+ * @packageDocumentation
4
+ */
5
+ /**
6
+ * Supported compression algorithms
7
+ */
8
+ export declare enum CompressionAlgorithm {
9
+ /** GZIP compression */
10
+ GZIP = "gzip",
11
+ /** Deflate compression */
12
+ DEFLATE = "deflate",
13
+ /** Brotli compression (Node.js 10.16.0+) */
14
+ BROTLI = "brotli"
15
+ }
16
+ /**
17
+ * Compression options
18
+ */
19
+ export interface CompressionOptions {
20
+ /** Compression algorithm to use */
21
+ algorithm?: CompressionAlgorithm;
22
+ /** Compression level (1-9, higher = better compression but slower) */
23
+ level?: number;
24
+ /** Encoding for string data */
25
+ encoding?: BufferEncoding;
26
+ }
27
+ /**
28
+ * Compression result with metrics
29
+ */
30
+ export interface CompressionResult {
31
+ /** Compressed data */
32
+ data: Buffer | string;
33
+ /** Original size in bytes */
34
+ originalSize: number;
35
+ /** Compressed size in bytes */
36
+ compressedSize: number;
37
+ /** Compression ratio (0-1) */
38
+ compressionRatio: number;
39
+ /** Time taken in milliseconds */
40
+ timeTakenMs: number;
41
+ /** Algorithm used */
42
+ algorithm: CompressionAlgorithm;
43
+ }
44
+ /**
45
+ * Main compression utility class
46
+ */
47
+ export declare class Compression {
48
+ /**
49
+ * Default compression options
50
+ */
51
+ private static readonly DEFAULT_OPTIONS;
52
+ /**
53
+ * Check if compression algorithm is supported
54
+ */
55
+ static isAlgorithmSupported(algorithm: CompressionAlgorithm): boolean;
56
+ /**
57
+ * Get supported algorithms for current environment
58
+ */
59
+ static getSupportedAlgorithms(): CompressionAlgorithm[];
60
+ /**
61
+ * Compress data
62
+ * @param input Data to compress (string or Buffer)
63
+ * @param options Compression options
64
+ * @returns Compressed data as Buffer
65
+ */
66
+ static compress(input: string | Buffer, options?: CompressionOptions): Promise<Buffer>;
67
+ /**
68
+ * Decompress data
69
+ * @param input Compressed data (Buffer or base64 string)
70
+ * @param options Compression options
71
+ * @returns Decompressed data as Buffer
72
+ */
73
+ static decompress(input: string | Buffer, options?: CompressionOptions): Promise<Buffer>;
74
+ /**
75
+ * Compress data with detailed metrics
76
+ * @param input Data to compress
77
+ * @param options Compression options
78
+ * @returns Compression result with metrics
79
+ */
80
+ static compressWithMetrics(input: string | Buffer, options?: CompressionOptions): Promise<CompressionResult>;
81
+ /**
82
+ * Compress buffer data using specified algorithm
83
+ */
84
+ private static compressBuffer;
85
+ /**
86
+ * Decompress buffer data using specified algorithm
87
+ */
88
+ private static decompressBuffer;
89
+ /**
90
+ * GZIP compression
91
+ */
92
+ private static compressGzip;
93
+ /**
94
+ * GZIP decompression
95
+ */
96
+ private static decompressGzip;
97
+ /**
98
+ * Deflate compression
99
+ */
100
+ private static compressDeflate;
101
+ /**
102
+ * Deflate decompression
103
+ */
104
+ private static decompressDeflate;
105
+ /**
106
+ * Brotli compression (Node.js 10.16.0+)
107
+ */
108
+ private static compressBrotli;
109
+ /**
110
+ * Brotli decompression (Node.js 10.16.0+)
111
+ */
112
+ private static decompressBrotli;
113
+ /**
114
+ * Create compression stream
115
+ * @param algorithm Compression algorithm
116
+ * @param options Compression options
117
+ * @returns Compression stream
118
+ */
119
+ static createCompressionStream(algorithm?: CompressionAlgorithm, options?: Omit<CompressionOptions, 'algorithm'>): NodeJS.ReadWriteStream;
120
+ /**
121
+ * Create decompression stream
122
+ * @param algorithm Compression algorithm
123
+ * @returns Decompression stream
124
+ */
125
+ static createDecompressionStream(algorithm?: CompressionAlgorithm): NodeJS.ReadWriteStream;
126
+ /**
127
+ * Stream compression
128
+ * @param readable Readable stream
129
+ * @param writable Writable stream
130
+ * @param options Compression options
131
+ */
132
+ static compressStream(readable: NodeJS.ReadableStream, writable: NodeJS.WritableStream, options?: CompressionOptions): Promise<void>;
133
+ /**
134
+ * Stream decompression
135
+ * @param readable Readable stream
136
+ * @param writable Writable stream
137
+ * @param options Compression options
138
+ */
139
+ static decompressStream(readable: NodeJS.ReadableStream, writable: NodeJS.WritableStream, options?: CompressionOptions): Promise<void>;
140
+ /**
141
+ * Validate input data
142
+ */
143
+ private static validateInput;
144
+ /**
145
+ * Validate compression options
146
+ */
147
+ private static validateOptions;
148
+ /**
149
+ * Wrap errors with CompressionError
150
+ */
151
+ private static wrapError;
152
+ }
153
+ /**
154
+ * Convenience function for compression
155
+ */
156
+ export declare function compress(input: string | Buffer, options?: CompressionOptions): Promise<Buffer>;
157
+ /**
158
+ * Convenience function for decompression
159
+ */
160
+ export declare function decompress(input: string | Buffer, options?: CompressionOptions): Promise<Buffer>;
161
+ /**
162
+ * Convenience function for compression with metrics
163
+ */
164
+ export declare function compressWithMetrics(input: string | Buffer, options?: CompressionOptions): Promise<CompressionResult>;
@@ -1,4 +1,4 @@
1
- import { type PerformanceConfig } from '../core/index.js';
1
+ import type { PerformanceConfig } from '../core/performance.js';
2
2
  export declare function validateConfig(config: Partial<PerformanceConfig>, defaultConfig: PerformanceConfig): PerformanceConfig;
3
3
  export declare function validatePerformanceSettings(settings: Partial<PerformanceConfig>): PerformanceConfig;
4
4
  export declare function mergeConfigs<T extends Record<string, any>>(base: T, override: Partial<T>): T;
@@ -1,3 +1,11 @@
1
- export * from './config.js';
2
- export * from './helpers.js';
3
- export * from './defineExtension.js';
1
+ /**
2
+ * Utils package exports
3
+ * @packageDocumentation
4
+ */
5
+ export { validateConfig, validatePerformanceSettings, mergeConfigs, } from './config.js';
6
+ export { isValidArrayIndex, ensurePositiveInteger, safeClone, getPathSegments, hasOwnProperty, } from './helpers.js';
7
+ export { defineExtension } from './defineExtension.js';
8
+ export { TimeoutManager, withTimeout, } from './timeout.js';
9
+ export { GenericPool, PoolManager, } from './pool.js';
10
+ export type { PoolConfig, Connection, } from './pool.js';
11
+ export { Compression, compress, decompress, compressWithMetrics, CompressionAlgorithm, type CompressionResult, type CompressionOptions, } from './compression.js';
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Generic connection pooling utilities
3
+ * @packageDocumentation
4
+ */
5
+ /**
6
+ * Connection resource interface
7
+ */
8
+ export interface Connection {
9
+ /** Unique connection ID */
10
+ id: string;
11
+ /** Connection metadata */
12
+ metadata?: Record<string, unknown>;
13
+ /** Check if connection is healthy */
14
+ isHealthy(): boolean;
15
+ /** Close/cleanup the connection */
16
+ close(): Promise<void>;
17
+ }
18
+ /**
19
+ * Pool configuration options
20
+ */
21
+ export interface PoolConfig<T extends Connection> {
22
+ /** Pool name for identification */
23
+ name?: string;
24
+ /** Minimum number of connections in pool */
25
+ minConnections?: number;
26
+ /** Maximum number of connections in pool */
27
+ maxConnections?: number;
28
+ /** Timeout for acquiring connection (ms) */
29
+ acquireTimeoutMs?: number;
30
+ /** Timeout for releasing connection (ms) */
31
+ releaseTimeoutMs?: number;
32
+ /** Maximum connection idle time before cleanup (ms) */
33
+ idleTimeoutMs?: number;
34
+ /** Maximum connection lifetime (ms) */
35
+ maxLifetimeMs?: number;
36
+ /** Health check interval (ms) */
37
+ healthCheckIntervalMs?: number;
38
+ /** Function to create new connection */
39
+ createConnection: () => Promise<T>;
40
+ /** Function to validate connection health */
41
+ validateConnection?: (connection: T) => boolean;
42
+ /** Function to destroy connection */
43
+ destroyConnection?: (connection: T) => Promise<void>;
44
+ }
45
+ /**
46
+ * Generic connection pool manager
47
+ */
48
+ export declare class GenericPool<T extends Connection> {
49
+ private readonly config;
50
+ private readonly connections;
51
+ private readonly pendingAcquires;
52
+ private isShuttingDown;
53
+ private healthCheckInterval?;
54
+ private stats;
55
+ constructor(config: PoolConfig<T>);
56
+ /**
57
+ * Validate pool configuration
58
+ */
59
+ private validateConfig;
60
+ /**
61
+ * Start periodic health checks
62
+ */
63
+ private startHealthChecks;
64
+ /**
65
+ * Stop health checks
66
+ */
67
+ private stopHealthChecks;
68
+ /**
69
+ * Acquire a connection from the pool
70
+ * @returns Promise resolving to connection
71
+ */
72
+ acquire(): Promise<T>;
73
+ /**
74
+ * Release a connection back to the pool
75
+ * @param connection Connection to release
76
+ */
77
+ release(connection: T): Promise<void>;
78
+ /**
79
+ * Try to fulfill pending acquire requests
80
+ */
81
+ private tryFulfillPendingAcquires;
82
+ /**
83
+ * Create and register a new connection
84
+ */
85
+ private createAndRegisterConnection;
86
+ /**
87
+ * Destroy a connection
88
+ */
89
+ private destroyConnection;
90
+ /**
91
+ * Clean up idle connections
92
+ */
93
+ private cleanupIdleConnections;
94
+ /**
95
+ * Clean up expired connections
96
+ */
97
+ private cleanupExpiredConnections;
98
+ /**
99
+ * Maintain minimum connections
100
+ */
101
+ private maintainMinConnections;
102
+ /**
103
+ * Get pool statistics
104
+ */
105
+ getStats(): {
106
+ totalConnections: number;
107
+ acquiredConnections: number;
108
+ availableConnections: number;
109
+ pendingAcquires: number;
110
+ isShuttingDown: boolean;
111
+ config: {
112
+ name: string;
113
+ minConnections: number;
114
+ maxConnections: number;
115
+ };
116
+ totalConnectionsCreated: number;
117
+ totalConnectionsDestroyed: number;
118
+ totalAcquireRequests: number;
119
+ totalAcquireTimeouts: number;
120
+ totalAcquireErrors: number;
121
+ totalReleaseRequests: number;
122
+ };
123
+ /**
124
+ * Get number of available connections
125
+ */
126
+ getAvailableCount(): number;
127
+ /**
128
+ * Drain the pool (graceful shutdown)
129
+ */
130
+ drain(): Promise<void>;
131
+ /**
132
+ * Execute a function with a connection from the pool
133
+ */
134
+ withConnection<R>(fn: (connection: T) => Promise<R>): Promise<R>;
135
+ }
136
+ /**
137
+ * Pool manager for multiple pools
138
+ */
139
+ export declare class PoolManager {
140
+ private pools;
141
+ /**
142
+ * Create or get a pool
143
+ */
144
+ createPool<T extends Connection>(config: PoolConfig<T>): GenericPool<T>;
145
+ /**
146
+ * Get a pool by name
147
+ */
148
+ getPool<T extends Connection>(name: string): GenericPool<T> | undefined;
149
+ /**
150
+ * Drain all pools
151
+ */
152
+ drainAll(): Promise<void>;
153
+ /**
154
+ * Get statistics for all pools
155
+ */
156
+ getAllStats(): Record<string, ReturnType<GenericPool<any>['getStats']>>;
157
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Timeout utilities for async operations
3
+ * @packageDocumentation
4
+ */
5
+ /**
6
+ * Timeout manager for async operations
7
+ */
8
+ export declare class TimeoutManager {
9
+ /**
10
+ * Execute a promise with a timeout
11
+ * @param promise Promise to execute
12
+ * @param timeoutMs Timeout duration in milliseconds
13
+ * @param errorMessage Optional custom error message
14
+ * @returns Promise result or throws TimeoutError
15
+ * @throws {TimeoutError} If operation times out
16
+ * @throws Any error thrown by the original promise
17
+ */
18
+ static withTimeout<T>(promise: Promise<T>, timeoutMs: number, errorMessage?: string): Promise<T>;
19
+ /**
20
+ * Create an AbortSignal that aborts after specified timeout
21
+ * @param timeoutMs Timeout duration in milliseconds
22
+ * @returns AbortSignal that aborts after timeout
23
+ */
24
+ static createTimeoutSignal(timeoutMs: number): AbortSignal;
25
+ /**
26
+ * Create a promise that resolves after specified delay
27
+ * @param delayMs Delay in milliseconds
28
+ * @returns Promise that resolves after delay
29
+ */
30
+ static delay(delayMs: number): Promise<void>;
31
+ /**
32
+ * Create a promise that rejects after specified timeout
33
+ * @param timeoutMs Timeout in milliseconds
34
+ * @param errorMessage Optional error message
35
+ * @returns Promise that rejects with TimeoutError after timeout
36
+ */
37
+ static timeoutPromise<T = never>(timeoutMs: number, errorMessage?: string): Promise<T>;
38
+ /**
39
+ * Race multiple promises with individual timeouts
40
+ * @param promises Array of promises to race
41
+ * @param timeoutMs Timeout for each promise
42
+ * @returns First promise to resolve, or rejects if all timeout
43
+ */
44
+ static raceWithTimeout<T>(promises: Promise<T>[], timeoutMs: number): Promise<T>;
45
+ /**
46
+ * Execute function with retry and timeout for each attempt
47
+ * @param fn Function to execute
48
+ * @param options Retry and timeout options
49
+ * @returns Function result
50
+ */
51
+ static retryWithTimeout<T>(fn: () => Promise<T>, options?: {
52
+ maxAttempts?: number;
53
+ timeoutPerAttempt?: number;
54
+ delayBetweenAttempts?: number;
55
+ backoffMultiplier?: number;
56
+ }): Promise<T>;
57
+ }
58
+ /**
59
+ * Create a timeout wrapper for async functions
60
+ * @param timeoutMs Timeout in milliseconds
61
+ * @param errorMessage Optional error message
62
+ * @returns Function wrapper that adds timeout
63
+ */
64
+ export declare function withTimeout<TArgs extends any[], TReturn>(timeoutMs: number, errorMessage?: string): (target: (...args: TArgs) => Promise<TReturn>, _context?: ClassMethodDecoratorContext) => (this: any, ...args: TArgs) => Promise<TReturn>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naman_deep_singh/utils",
3
- "version": "2.3.0",
3
+ "version": "2.6.0",
4
4
  "description": "Universal JavaScript prototype extensions for common development utilities",
5
5
  "type": "module",
6
6
  "main": "./dist/cjs/index.js",
@@ -81,6 +81,7 @@
81
81
  "typescript": "^5.9.3"
82
82
  },
83
83
  "dependencies": {
84
+ "@naman_deep_singh/errors": "^2.3.0",
84
85
  "@types/node": "^25.0.1"
85
86
  },
86
87
  "publishConfig": {