@naman_deep_singh/utils 2.4.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.
@@ -0,0 +1,455 @@
1
+ "use strict";
2
+ /**
3
+ * Compression utilities for data compression/decompression
4
+ * @packageDocumentation
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.Compression = exports.CompressionAlgorithm = void 0;
41
+ exports.compress = compress;
42
+ exports.decompress = decompress;
43
+ exports.compressWithMetrics = compressWithMetrics;
44
+ const CompressionError_js_1 = require("../errors/CompressionError.js");
45
+ /**
46
+ * Supported compression algorithms
47
+ */
48
+ var CompressionAlgorithm;
49
+ (function (CompressionAlgorithm) {
50
+ /** GZIP compression */
51
+ CompressionAlgorithm["GZIP"] = "gzip";
52
+ /** Deflate compression */
53
+ CompressionAlgorithm["DEFLATE"] = "deflate";
54
+ /** Brotli compression (Node.js 10.16.0+) */
55
+ CompressionAlgorithm["BROTLI"] = "brotli";
56
+ })(CompressionAlgorithm || (exports.CompressionAlgorithm = CompressionAlgorithm = {}));
57
+ /**
58
+ * Main compression utility class
59
+ */
60
+ class Compression {
61
+ /**
62
+ * Check if compression algorithm is supported
63
+ */
64
+ static isAlgorithmSupported(algorithm) {
65
+ switch (algorithm) {
66
+ case CompressionAlgorithm.GZIP:
67
+ case CompressionAlgorithm.DEFLATE:
68
+ return true;
69
+ case CompressionAlgorithm.BROTLI:
70
+ // Brotli requires Node.js 10.16.0+
71
+ if (typeof process !== 'undefined' && process.versions?.node) {
72
+ const [major, minor, _patch] = process.versions.node
73
+ .split('.')
74
+ .map(Number);
75
+ // Brotli support from Node.js 10.16.0
76
+ return major > 10 || (major === 10 && minor >= 16);
77
+ }
78
+ return false;
79
+ default:
80
+ return false;
81
+ }
82
+ }
83
+ /**
84
+ * Get supported algorithms for current environment
85
+ */
86
+ static getSupportedAlgorithms() {
87
+ const algorithms = [
88
+ CompressionAlgorithm.GZIP,
89
+ CompressionAlgorithm.DEFLATE,
90
+ ];
91
+ if (this.isAlgorithmSupported(CompressionAlgorithm.BROTLI)) {
92
+ algorithms.push(CompressionAlgorithm.BROTLI);
93
+ }
94
+ return algorithms;
95
+ }
96
+ /**
97
+ * Compress data
98
+ * @param input Data to compress (string or Buffer)
99
+ * @param options Compression options
100
+ * @returns Compressed data as Buffer
101
+ */
102
+ static async compress(input, options = {}) {
103
+ const opts = { ...this.DEFAULT_OPTIONS, ...options };
104
+ try {
105
+ this.validateInput(input);
106
+ this.validateOptions(opts);
107
+ const buffer = typeof input === 'string' ? Buffer.from(input, opts.encoding) : input;
108
+ const compressed = await this.compressBuffer(buffer, opts);
109
+ return compressed;
110
+ }
111
+ catch (error) {
112
+ throw this.wrapError(error, 'compress', opts.algorithm, input);
113
+ }
114
+ }
115
+ /**
116
+ * Decompress data
117
+ * @param input Compressed data (Buffer or base64 string)
118
+ * @param options Compression options
119
+ * @returns Decompressed data as Buffer
120
+ */
121
+ static async decompress(input, options = {}) {
122
+ const opts = { ...this.DEFAULT_OPTIONS, ...options };
123
+ try {
124
+ this.validateInput(input);
125
+ const buffer = typeof input === 'string' ? Buffer.from(input, 'base64') : input;
126
+ const decompressed = await this.decompressBuffer(buffer, opts);
127
+ return decompressed;
128
+ }
129
+ catch (error) {
130
+ throw this.wrapError(error, 'decompress', opts.algorithm, input);
131
+ }
132
+ }
133
+ /**
134
+ * Compress data with detailed metrics
135
+ * @param input Data to compress
136
+ * @param options Compression options
137
+ * @returns Compression result with metrics
138
+ */
139
+ static async compressWithMetrics(input, options = {}) {
140
+ const startTime = performance.now();
141
+ const opts = { ...this.DEFAULT_OPTIONS, ...options };
142
+ try {
143
+ this.validateInput(input);
144
+ this.validateOptions(opts);
145
+ const buffer = typeof input === 'string' ? Buffer.from(input, opts.encoding) : input;
146
+ const originalSize = buffer.length;
147
+ const compressed = await this.compressBuffer(buffer, opts);
148
+ const endTime = performance.now();
149
+ const compressedSize = compressed.length;
150
+ const compressionRatio = compressedSize / originalSize;
151
+ return {
152
+ data: opts.encoding === 'base64'
153
+ ? compressed.toString('base64')
154
+ : compressed,
155
+ originalSize,
156
+ compressedSize,
157
+ compressionRatio,
158
+ timeTakenMs: endTime - startTime,
159
+ algorithm: opts.algorithm,
160
+ };
161
+ }
162
+ catch (error) {
163
+ throw this.wrapError(error, 'compressWithMetrics', opts.algorithm, input);
164
+ }
165
+ }
166
+ /**
167
+ * Compress buffer data using specified algorithm
168
+ */
169
+ static async compressBuffer(buffer, options) {
170
+ switch (options.algorithm) {
171
+ case CompressionAlgorithm.GZIP:
172
+ return this.compressGzip(buffer, options.level);
173
+ case CompressionAlgorithm.DEFLATE:
174
+ return this.compressDeflate(buffer, options.level);
175
+ case CompressionAlgorithm.BROTLI:
176
+ return this.compressBrotli(buffer, options.level);
177
+ default:
178
+ throw new CompressionError_js_1.CompressionError(`Unsupported algorithm: ${options.algorithm}`, options.algorithm);
179
+ }
180
+ }
181
+ /**
182
+ * Decompress buffer data using specified algorithm
183
+ */
184
+ static async decompressBuffer(buffer, options) {
185
+ switch (options.algorithm) {
186
+ case CompressionAlgorithm.GZIP:
187
+ return this.decompressGzip(buffer);
188
+ case CompressionAlgorithm.DEFLATE:
189
+ return this.decompressDeflate(buffer);
190
+ case CompressionAlgorithm.BROTLI:
191
+ return this.decompressBrotli(buffer);
192
+ default:
193
+ throw new CompressionError_js_1.CompressionError(`Unsupported algorithm: ${options.algorithm}`, options.algorithm);
194
+ }
195
+ }
196
+ /**
197
+ * GZIP compression
198
+ */
199
+ static async compressGzip(buffer, level) {
200
+ const { gzip } = await Promise.resolve().then(() => __importStar(require('zlib')));
201
+ return new Promise((resolve, reject) => {
202
+ gzip(buffer, { level }, (error, result) => {
203
+ if (error)
204
+ reject(error);
205
+ else
206
+ resolve(result);
207
+ });
208
+ });
209
+ }
210
+ /**
211
+ * GZIP decompression
212
+ */
213
+ static async decompressGzip(buffer) {
214
+ const { gunzip } = await Promise.resolve().then(() => __importStar(require('zlib')));
215
+ return new Promise((resolve, reject) => {
216
+ gunzip(buffer, (error, result) => {
217
+ if (error)
218
+ reject(error);
219
+ else
220
+ resolve(result);
221
+ });
222
+ });
223
+ }
224
+ /**
225
+ * Deflate compression
226
+ */
227
+ static async compressDeflate(buffer, level) {
228
+ const { deflate } = await Promise.resolve().then(() => __importStar(require('zlib')));
229
+ return new Promise((resolve, reject) => {
230
+ deflate(buffer, { level }, (error, result) => {
231
+ if (error)
232
+ reject(error);
233
+ else
234
+ resolve(result);
235
+ });
236
+ });
237
+ }
238
+ /**
239
+ * Deflate decompression
240
+ */
241
+ static async decompressDeflate(buffer) {
242
+ const { inflate } = await Promise.resolve().then(() => __importStar(require('zlib')));
243
+ return new Promise((resolve, reject) => {
244
+ inflate(buffer, (error, result) => {
245
+ if (error)
246
+ reject(error);
247
+ else
248
+ resolve(result);
249
+ });
250
+ });
251
+ }
252
+ /**
253
+ * Brotli compression (Node.js 10.16.0+)
254
+ */
255
+ static async compressBrotli(buffer, level) {
256
+ const zlib = await Promise.resolve().then(() => __importStar(require('zlib')));
257
+ if (!zlib.brotliCompress) {
258
+ throw new CompressionError_js_1.CompressionError('Brotli compression requires Node.js 10.16.0+', CompressionAlgorithm.BROTLI, {
259
+ nodeVersion: process?.version || 'unknown',
260
+ requiredVersion: '>=10.16.0',
261
+ });
262
+ }
263
+ return new Promise((resolve, reject) => {
264
+ zlib.brotliCompress(buffer, {
265
+ params: {
266
+ [zlib.constants.BROTLI_PARAM_QUALITY]: level,
267
+ [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
268
+ },
269
+ }, (error, result) => {
270
+ if (error)
271
+ reject(error);
272
+ else
273
+ resolve(result);
274
+ });
275
+ });
276
+ }
277
+ /**
278
+ * Brotli decompression (Node.js 10.16.0+)
279
+ */
280
+ static async decompressBrotli(buffer) {
281
+ const zlib = await Promise.resolve().then(() => __importStar(require('zlib')));
282
+ if (!zlib.brotliDecompress) {
283
+ throw new CompressionError_js_1.CompressionError('Brotli decompression requires Node.js 10.16.0+', CompressionAlgorithm.BROTLI, {
284
+ nodeVersion: process?.version || 'unknown',
285
+ requiredVersion: '>=10.16.0',
286
+ });
287
+ }
288
+ return new Promise((resolve, reject) => {
289
+ zlib.brotliDecompress(buffer, (error, result) => {
290
+ if (error)
291
+ reject(error);
292
+ else
293
+ resolve(result);
294
+ });
295
+ });
296
+ }
297
+ /**
298
+ * Create compression stream
299
+ * @param algorithm Compression algorithm
300
+ * @param options Compression options
301
+ * @returns Compression stream
302
+ */
303
+ static createCompressionStream(algorithm = CompressionAlgorithm.GZIP, options = {}) {
304
+ const opts = { ...this.DEFAULT_OPTIONS, ...options, algorithm };
305
+ this.validateOptions(opts);
306
+ switch (algorithm) {
307
+ case CompressionAlgorithm.GZIP:
308
+ return require('zlib').createGzip({ level: opts.level });
309
+ case CompressionAlgorithm.DEFLATE:
310
+ return require('zlib').createDeflate({ level: opts.level });
311
+ case CompressionAlgorithm.BROTLI:
312
+ const zlib = require('zlib');
313
+ if (!zlib.createBrotliCompress) {
314
+ throw new CompressionError_js_1.CompressionError('Brotli stream compression requires Node.js 10.16.0+', CompressionAlgorithm.BROTLI);
315
+ }
316
+ return zlib.createBrotliCompress({
317
+ params: {
318
+ [zlib.constants.BROTLI_PARAM_QUALITY]: opts.level,
319
+ },
320
+ });
321
+ default:
322
+ throw new CompressionError_js_1.CompressionError(`Unsupported algorithm for streaming: ${algorithm}`, algorithm);
323
+ }
324
+ }
325
+ /**
326
+ * Create decompression stream
327
+ * @param algorithm Compression algorithm
328
+ * @returns Decompression stream
329
+ */
330
+ static createDecompressionStream(algorithm = CompressionAlgorithm.GZIP) {
331
+ switch (algorithm) {
332
+ case CompressionAlgorithm.GZIP:
333
+ return require('zlib').createGunzip();
334
+ case CompressionAlgorithm.DEFLATE:
335
+ return require('zlib').createInflate();
336
+ case CompressionAlgorithm.BROTLI:
337
+ const zlib = require('zlib');
338
+ if (!zlib.createBrotliDecompress) {
339
+ throw new CompressionError_js_1.CompressionError('Brotli stream decompression requires Node.js 10.16.0+', CompressionAlgorithm.BROTLI);
340
+ }
341
+ return zlib.createBrotliDecompress();
342
+ default:
343
+ throw new CompressionError_js_1.CompressionError(`Unsupported algorithm for streaming: ${algorithm}`, algorithm);
344
+ }
345
+ }
346
+ /**
347
+ * Stream compression
348
+ * @param readable Readable stream
349
+ * @param writable Writable stream
350
+ * @param options Compression options
351
+ */
352
+ static async compressStream(readable, writable, options = {}) {
353
+ return new Promise((resolve, reject) => {
354
+ const compressor = this.createCompressionStream(options.algorithm, options);
355
+ readable
356
+ .pipe(compressor)
357
+ .pipe(writable)
358
+ .on('finish', resolve)
359
+ .on('error', reject);
360
+ });
361
+ }
362
+ /**
363
+ * Stream decompression
364
+ * @param readable Readable stream
365
+ * @param writable Writable stream
366
+ * @param options Compression options
367
+ */
368
+ static async decompressStream(readable, writable, options = {}) {
369
+ return new Promise((resolve, reject) => {
370
+ const decompressor = this.createDecompressionStream(options.algorithm);
371
+ readable
372
+ .pipe(decompressor)
373
+ .pipe(writable)
374
+ .on('finish', resolve)
375
+ .on('error', reject);
376
+ });
377
+ }
378
+ /**
379
+ * Validate input data
380
+ */
381
+ static validateInput(input) {
382
+ if (input === null || input === undefined) {
383
+ throw new CompressionError_js_1.CompressionError('Input cannot be null or undefined');
384
+ }
385
+ if (typeof input !== 'string' && !Buffer.isBuffer(input)) {
386
+ throw new CompressionError_js_1.CompressionError(`Input must be string or Buffer, got ${typeof input}`);
387
+ }
388
+ if (typeof input === 'string' && input.length === 0) {
389
+ throw new CompressionError_js_1.CompressionError('Input string cannot be empty');
390
+ }
391
+ if (Buffer.isBuffer(input) && input.length === 0) {
392
+ throw new CompressionError_js_1.CompressionError('Input buffer cannot be empty');
393
+ }
394
+ }
395
+ /**
396
+ * Validate compression options
397
+ */
398
+ static validateOptions(options) {
399
+ if (!Object.values(CompressionAlgorithm).includes(options.algorithm)) {
400
+ throw new CompressionError_js_1.CompressionError(`Invalid algorithm: ${options.algorithm}`, options.algorithm);
401
+ }
402
+ if (options.level < 1 || options.level > 9) {
403
+ throw new CompressionError_js_1.CompressionError(`Compression level must be between 1-9, got ${options.level}`, options.algorithm, { level: options.level });
404
+ }
405
+ if (!this.isAlgorithmSupported(options.algorithm)) {
406
+ throw new CompressionError_js_1.CompressionError(`Algorithm not supported: ${options.algorithm}`, options.algorithm, {
407
+ supportedAlgorithms: this.getSupportedAlgorithms(),
408
+ nodeVersion: process?.version || 'unknown',
409
+ });
410
+ }
411
+ }
412
+ /**
413
+ * Wrap errors with CompressionError
414
+ */
415
+ static wrapError(error, operation, algorithm, input) {
416
+ if (error instanceof CompressionError_js_1.CompressionError) {
417
+ return error;
418
+ }
419
+ const errorMessage = error instanceof Error ? error.message : String(error);
420
+ const inputInfo = Buffer.isBuffer(input)
421
+ ? { size: input.length, type: 'buffer' }
422
+ : { size: input.length, type: 'string' };
423
+ return new CompressionError_js_1.CompressionError(`Failed to ${operation} with ${algorithm}: ${errorMessage}`, algorithm, {
424
+ operation,
425
+ input: inputInfo,
426
+ }, error instanceof Error ? error : undefined);
427
+ }
428
+ }
429
+ exports.Compression = Compression;
430
+ /**
431
+ * Default compression options
432
+ */
433
+ Compression.DEFAULT_OPTIONS = {
434
+ algorithm: CompressionAlgorithm.GZIP,
435
+ level: 6,
436
+ encoding: 'utf8',
437
+ };
438
+ /**
439
+ * Convenience function for compression
440
+ */
441
+ async function compress(input, options = {}) {
442
+ return Compression.compress(input, options);
443
+ }
444
+ /**
445
+ * Convenience function for decompression
446
+ */
447
+ async function decompress(input, options = {}) {
448
+ return Compression.decompress(input, options);
449
+ }
450
+ /**
451
+ * Convenience function for compression with metrics
452
+ */
453
+ async function compressWithMetrics(input, options = {}) {
454
+ return Compression.compressWithMetrics(input, options);
455
+ }
@@ -1,16 +1,37 @@
1
1
  "use strict";
2
+ /**
3
+ * Utils package exports
4
+ * @packageDocumentation
5
+ */
2
6
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defineExtension = exports.hasOwnProperty = exports.getPathSegments = exports.safeClone = exports.ensurePositiveInteger = exports.isValidArrayIndex = exports.mergeConfigs = exports.validatePerformanceSettings = exports.validateConfig = void 0;
4
- // Re-export all utilities
7
+ exports.CompressionAlgorithm = exports.compressWithMetrics = exports.decompress = exports.compress = exports.Compression = exports.PoolManager = exports.GenericPool = exports.withTimeout = exports.TimeoutManager = exports.defineExtension = exports.hasOwnProperty = exports.getPathSegments = exports.safeClone = exports.ensurePositiveInteger = exports.isValidArrayIndex = exports.mergeConfigs = exports.validatePerformanceSettings = exports.validateConfig = void 0;
8
+ // Export configuration utilities
5
9
  var config_js_1 = require("./config.js");
6
10
  Object.defineProperty(exports, "validateConfig", { enumerable: true, get: function () { return config_js_1.validateConfig; } });
7
11
  Object.defineProperty(exports, "validatePerformanceSettings", { enumerable: true, get: function () { return config_js_1.validatePerformanceSettings; } });
8
12
  Object.defineProperty(exports, "mergeConfigs", { enumerable: true, get: function () { return config_js_1.mergeConfigs; } });
13
+ // Export helper utilities
9
14
  var helpers_js_1 = require("./helpers.js");
10
15
  Object.defineProperty(exports, "isValidArrayIndex", { enumerable: true, get: function () { return helpers_js_1.isValidArrayIndex; } });
11
16
  Object.defineProperty(exports, "ensurePositiveInteger", { enumerable: true, get: function () { return helpers_js_1.ensurePositiveInteger; } });
12
17
  Object.defineProperty(exports, "safeClone", { enumerable: true, get: function () { return helpers_js_1.safeClone; } });
13
18
  Object.defineProperty(exports, "getPathSegments", { enumerable: true, get: function () { return helpers_js_1.getPathSegments; } });
14
19
  Object.defineProperty(exports, "hasOwnProperty", { enumerable: true, get: function () { return helpers_js_1.hasOwnProperty; } });
20
+ // Export extension utilities
15
21
  var defineExtension_js_1 = require("./defineExtension.js");
16
22
  Object.defineProperty(exports, "defineExtension", { enumerable: true, get: function () { return defineExtension_js_1.defineExtension; } });
23
+ // Export timeout utilities
24
+ var timeout_js_1 = require("./timeout.js");
25
+ Object.defineProperty(exports, "TimeoutManager", { enumerable: true, get: function () { return timeout_js_1.TimeoutManager; } });
26
+ Object.defineProperty(exports, "withTimeout", { enumerable: true, get: function () { return timeout_js_1.withTimeout; } });
27
+ // Export pool utilities
28
+ var pool_js_1 = require("./pool.js");
29
+ Object.defineProperty(exports, "GenericPool", { enumerable: true, get: function () { return pool_js_1.GenericPool; } });
30
+ Object.defineProperty(exports, "PoolManager", { enumerable: true, get: function () { return pool_js_1.PoolManager; } });
31
+ // Export compression utilities
32
+ var compression_js_1 = require("./compression.js");
33
+ Object.defineProperty(exports, "Compression", { enumerable: true, get: function () { return compression_js_1.Compression; } });
34
+ Object.defineProperty(exports, "compress", { enumerable: true, get: function () { return compression_js_1.compress; } });
35
+ Object.defineProperty(exports, "decompress", { enumerable: true, get: function () { return compression_js_1.decompress; } });
36
+ Object.defineProperty(exports, "compressWithMetrics", { enumerable: true, get: function () { return compression_js_1.compressWithMetrics; } });
37
+ Object.defineProperty(exports, "CompressionAlgorithm", { enumerable: true, get: function () { return compression_js_1.CompressionAlgorithm; } });