@catbee/utils 2.0.0-next.0 → 2.0.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 (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +102 -52
  3. package/array/index.cjs +215 -74
  4. package/array/index.d.ts +345 -2
  5. package/array/index.mjs +201 -74
  6. package/async/index.cjs +116 -39
  7. package/async/index.d.ts +292 -2
  8. package/async/index.mjs +116 -40
  9. package/cache/index.cjs +2 -2
  10. package/cache/index.d.ts +156 -2
  11. package/cache/index.mjs +3 -3
  12. package/config/index.cjs +80 -66
  13. package/config/index.d.ts +65 -3
  14. package/config/index.mjs +77 -65
  15. package/context-store/index.cjs +2 -3
  16. package/context-store/index.d.ts +193 -2
  17. package/context-store/index.mjs +2 -3
  18. package/crypto/index.cjs +55 -5
  19. package/crypto/index.d.ts +225 -2
  20. package/crypto/index.mjs +52 -7
  21. package/date/index.cjs +676 -2
  22. package/date/index.d.ts +676 -2
  23. package/date/index.mjs +665 -3
  24. package/decorator/index.cjs +2172 -0
  25. package/{decorators/decorators.utils.d.ts → decorator/index.d.ts} +58 -54
  26. package/decorator/index.mjs +2131 -0
  27. package/{dir → directory}/index.cjs +5 -4
  28. package/{dir/dir.utils.d.ts → directory/index.d.ts} +24 -21
  29. package/{dir → directory}/index.mjs +5 -4
  30. package/env/index.cjs +100 -68
  31. package/env/index.d.ts +391 -2
  32. package/env/index.mjs +100 -68
  33. package/exception/index.cjs +1 -1
  34. package/exception/index.d.ts +233 -2
  35. package/exception/index.mjs +1 -1
  36. package/fs/index.cjs +71 -37
  37. package/fs/index.d.ts +206 -2
  38. package/fs/index.mjs +65 -35
  39. package/http-status-codes/index.cjs +1 -1
  40. package/http-status-codes/index.d.ts +268 -2
  41. package/http-status-codes/index.mjs +1 -1
  42. package/id/index.cjs +1 -1
  43. package/id/index.d.ts +38 -2
  44. package/id/index.mjs +1 -1
  45. package/index.cjs +13 -13
  46. package/index.d.ts +5 -5
  47. package/index.mjs +5 -5
  48. package/logger/index.cjs +13 -15
  49. package/logger/index.d.ts +190 -2
  50. package/logger/index.mjs +14 -16
  51. package/middleware/index.cjs +1 -1
  52. package/middleware/index.d.ts +104 -2
  53. package/middleware/index.mjs +1 -1
  54. package/object/index.cjs +379 -0
  55. package/{obj/obj.utils.d.ts → object/index.d.ts} +73 -33
  56. package/object/index.mjs +360 -0
  57. package/package.json +41 -23
  58. package/performance/index.cjs +4 -4
  59. package/performance/index.d.ts +139 -2
  60. package/performance/index.mjs +4 -4
  61. package/request/index.cjs +37 -25
  62. package/request/index.d.ts +242 -3
  63. package/request/index.mjs +37 -25
  64. package/response/index.cjs +1 -1
  65. package/response/index.d.ts +319 -3
  66. package/response/index.mjs +1 -1
  67. package/server/index.cjs +249 -146
  68. package/server/index.d.ts +866 -5
  69. package/server/index.mjs +248 -144
  70. package/stream/index.cjs +1 -1
  71. package/stream/index.d.ts +91 -2
  72. package/stream/index.mjs +1 -1
  73. package/string/index.cjs +34 -1
  74. package/string/index.d.ts +146 -2
  75. package/string/index.mjs +31 -2
  76. package/type/index.cjs +19 -2
  77. package/type/index.d.ts +144 -2
  78. package/type/index.mjs +17 -3
  79. package/types/index.cjs +1 -1
  80. package/types/index.d.ts +775 -5
  81. package/types/index.mjs +1 -1
  82. package/url/index.cjs +63 -5
  83. package/url/index.d.ts +200 -2
  84. package/url/index.mjs +59 -6
  85. package/{validate → validation}/index.cjs +91 -44
  86. package/{validate/validate.utils.d.ts → validation/index.d.ts} +33 -24
  87. package/{validate → validation}/index.mjs +87 -44
  88. package/array/array.utils.d.ts +0 -191
  89. package/async/async.utils.d.ts +0 -296
  90. package/cache/cache.utils.d.ts +0 -176
  91. package/config/config.d.ts +0 -57
  92. package/context-store/context-store.utils.d.ts +0 -212
  93. package/crypto/crypto.utils.d.ts +0 -183
  94. package/date/date.utils.d.ts +0 -190
  95. package/decorators/index.cjs +0 -913
  96. package/decorators/index.d.ts +0 -25
  97. package/decorators/index.mjs +0 -872
  98. package/dir/index.d.ts +0 -25
  99. package/env/env.utils.d.ts +0 -400
  100. package/exception/exception.utils.d.ts +0 -253
  101. package/fs/fs.utils.d.ts +0 -196
  102. package/http-status-codes/http-status-codes.d.ts +0 -289
  103. package/id/id.utils.d.ts +0 -59
  104. package/logger/logger.utils.d.ts +0 -210
  105. package/middleware/middleware.utils.d.ts +0 -123
  106. package/obj/index.cjs +0 -317
  107. package/obj/index.d.ts +0 -25
  108. package/obj/index.mjs +0 -301
  109. package/performance/performance.utils.d.ts +0 -159
  110. package/request/request.utils.d.ts +0 -109
  111. package/response/response.utils.d.ts +0 -186
  112. package/server/server.builder.d.ts +0 -531
  113. package/server/server.d.ts +0 -303
  114. package/stream/stream.utils.d.ts +0 -111
  115. package/string/string.utils.d.ts +0 -124
  116. package/type/type.utils.d.ts +0 -129
  117. package/types/api-response.d.ts +0 -175
  118. package/types/common.d.ts +0 -148
  119. package/types/config.d.ts +0 -88
  120. package/types/server.d.ts +0 -291
  121. package/url/url.utils.d.ts +0 -164
  122. package/validate/index.d.ts +0 -25
@@ -1,210 +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 pino from 'pino';
26
- import type { Logger as PinoLogger } from 'pino';
27
- /**
28
- * Logger type for application-wide logging.
29
- */
30
- export type Logger = PinoLogger;
31
- /**
32
- * Logger levels for application-wide logging.
33
- */
34
- export type LoggerLevels = pino.Level;
35
- export declare const defaultSensitiveFields: string[];
36
- /**
37
- * Sets the global redaction censor function used throughout the application for log redaction.
38
- *
39
- * Use this function to customize how sensitive data is redacted in logs. The provided function
40
- * will replace the default censor implementation.
41
- *
42
- * @example
43
- * ```typescript
44
- * // Custom censor that redacts only specific values
45
- * setRedactCensor((value, path, sensitiveFields) => {
46
- * if (path.includes('password')) return '***';
47
- * return value;
48
- * });
49
- * ```
50
- *
51
- * @param fn - The redaction censor function to use globally. This function receives:
52
- * - value: The data value to potentially redact
53
- * - path: Array of strings representing the path to the value in the object
54
- * - sensitiveFields: Optional array of field names to consider sensitive
55
- * @returns void
56
- */
57
- export declare function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string): void;
58
- /**
59
- * Gets the current global redaction censor function used for log redaction.
60
- *
61
- * This function is called internally by the logger when determining how to redact
62
- * sensitive information. It can also be used to access the current censor implementation
63
- * for composition or extension.
64
- *
65
- * @example
66
- * ```typescript
67
- * const currentCensor = getRedactCensor();
68
- * // Create an enhanced censor that extends the current one
69
- * setRedactCensor((value, path, fields) => {
70
- * // Add custom logic before delegating to current censor
71
- * if (someCondition) return customHandling();
72
- * return currentCensor(value, path, fields);
73
- * });
74
- * ```
75
- *
76
- * @returns The current redaction censor function
77
- */
78
- export declare function getRedactCensor(): (value: unknown, path: string[], sensitiveFields?: string[]) => string;
79
- /**
80
- * Convenience function to redact sensitive data using the current global redact censor.
81
- *
82
- * This is a direct wrapper around the global censor function that simplifies usage
83
- * in application code without needing to access the censor function directly.
84
- *
85
- * @example
86
- * ```typescript
87
- * // Redact a potential sensitive value
88
- * const safeValue = redact(value, ['user', 'apiKey']);
89
- * ```
90
- *
91
- * @param value - The value to potentially redact
92
- * @param path - Array of strings representing the path to the value in the object
93
- * @param sensitiveFields - Optional array of field names to consider sensitive
94
- * @returns The redacted string value or "***" for redacted content
95
- */
96
- export declare function redact(value: unknown, path: string[], sensitiveFields?: string[]): string;
97
- /**
98
- * @deprecated Use addSensitiveFields instead.
99
- *
100
- * Extends the current redaction function with additional fields to redact.
101
- *
102
- * This function wraps the existing censor while adding more fields to be considered
103
- * sensitive without replacing the entire redaction logic.
104
- *
105
- * @example
106
- * ```typescript
107
- * // Add custom fields to be redacted in all future redaction operations
108
- * addRedactFields(['customerId', 'accountNumber']);
109
- * ```
110
- *
111
- * @param fields - Array of additional field names to redact
112
- */
113
- export declare function addRedactFields(fields: string[]): void;
114
- /**
115
- * Retrieves the expanded list of sensitive fields.
116
- *
117
- * This function expands the default sensitive fields into their various naming
118
- * conventions (e.g., camelCase, snake_case) and caches the result for efficiency.
119
- *
120
- * @returns Array of expanded sensitive field names
121
- */
122
- export declare function getExpandedSensitiveFields(): string[];
123
- /**
124
- * Replaces the default list of sensitive fields with a new list.
125
- *
126
- * This is useful when you want complete control over what fields are considered
127
- * sensitive by default, rather than using the library's built-in list.
128
- *
129
- * @example
130
- * ```typescript
131
- * // Replace default sensitive fields with a custom list
132
- * setSensitiveFields(['password', 'ssn', 'creditCard']);
133
- * ```
134
- *
135
- * @param fields - Array of field names to set as the new default sensitive fields
136
- */
137
- export declare function setSensitiveFields(fields: string[]): void;
138
- /**
139
- * Adds additional field names to the default sensitive fields list.
140
- *
141
- * This preserves the existing sensitive fields while adding new ones for
142
- * application-specific sensitive data.
143
- *
144
- * @example
145
- * ```typescript
146
- * // Add domain-specific sensitive fields to the default list
147
- * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
148
- * ```
149
- *
150
- * @param fields - Array of additional field names to add to the sensitive fields list
151
- */
152
- export declare function addSensitiveFields(fields: string[]): void;
153
- /**
154
- * Use an object compatible with either modern or legacy global scopes.
155
- */
156
- export declare const _globalThis: typeof globalThis;
157
- /**
158
- * Retrieves the current logger instance:
159
- * - Returns a request-scoped logger from AsyncLocalStorage if available
160
- * - Falls back to the global (singleton) logger
161
- * - Initializes the global logger if not created yet
162
- * - If newInstance is true, returns a fresh logger without any context
163
- *
164
- * @param {boolean} newInstance - If true, returns a fresh logger without any context
165
- * @returns {Logger} The logger instance (request-bound or global root logger or fresh instance)
166
- */
167
- export declare function getLogger(newInstance?: boolean): PinoLogger;
168
- /**
169
- * Creates a child logger with additional context.
170
- *
171
- * @param {Record<string, any>} bindings - Properties to attach to all log records
172
- * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
173
- * @returns {Logger} Child logger with merged context
174
- */
175
- export declare function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger;
176
- /**
177
- * Creates a request-scoped logger with request ID and stores it in context
178
- *
179
- * @param {string} requestId - Unique request identifier
180
- * @param {object} [additionalContext] - Additional context to include in logs
181
- * @returns {Logger} Request-scoped logger instance
182
- */
183
- export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): PinoLogger;
184
- /**
185
- * Utility to safely log errors with proper stack trace extraction
186
- *
187
- * @param {Error|unknown} error - Error object to log
188
- * @param {string} [message] - Optional message to include
189
- * @param {Record<string, any>} [context] - Additional context properties
190
- */
191
- export declare function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void;
192
- /**
193
- * Expands multiple sensitive field names into their variants.
194
- * Useful to match fields like `api_key`, `apiKey`, `apikey`, `APIKEY`, etc.
195
- */
196
- export declare function expandSensitiveFields(fields: string[]): string[];
197
- /**
198
- * Generates multiple variants of a sensitive field name.
199
- * Useful to match fields like `api_key`, `apiKey`, `apikey`, `APIKEY`, etc.
200
- */
201
- export declare function expandSensitiveField(field: string): string[];
202
- /**
203
- * Generates wildcard paths up to the given depth.
204
- *
205
- * depth = 2 →
206
- * password
207
- * *.password
208
- * *.*.password
209
- */
210
- export declare function generateDeepPaths(field: string, depth: number): string[];
@@ -1,123 +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 type { Request, Response, NextFunction } from 'express';
26
- export type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
27
- /**
28
- * Attaches a unique request ID to each request.
29
- * Useful for request tracing and correlation between logs.
30
- *
31
- * @param {object} [options] - Configuration options
32
- * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
33
- * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
34
- * @param {() => string} [options.generator] - Custom ID generator function
35
- * @returns {Middleware} Express-compatible middleware
36
- */
37
- export declare function requestId(options?: {
38
- headerName?: string;
39
- exposeHeader?: boolean;
40
- generator?: () => string;
41
- }): Middleware;
42
- /**
43
- * Measures request processing time and logs or adds it to response headers.
44
- *
45
- * @param {object} [options] - Configuration options
46
- * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
47
- * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
48
- * @returns {Middleware} Express-compatible middleware
49
- */
50
- export declare function responseTime(options?: {
51
- addHeader?: boolean;
52
- logOnComplete?: boolean;
53
- }): (req: Request, res: Response, next: NextFunction) => void;
54
- /**
55
- * Request timeout middleware.
56
- * Aborts requests that take too long to process.
57
- *
58
- * @param {number} [timeoutMs=30000] - Timeout in milliseconds
59
- * @returns {Middleware} Express-compatible middleware
60
- */
61
- export declare function timeout(timeoutMs?: number): Middleware;
62
- /**
63
- * Creates an Express middleware that initializes a per-request context.
64
- *
65
- * @param {object} [options] - Optional configuration
66
- * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
67
- * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
68
- * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
69
- */
70
- export declare function setupRequestContext(options?: {
71
- headerName?: string;
72
- autoLog?: boolean;
73
- }): Middleware;
74
- export interface ErrorHandlerOptions {
75
- /** Whether to log errors (default: true) */
76
- logErrors?: boolean;
77
- /** Whether to include error details in non-production (default: false) */
78
- includeDetails?: boolean;
79
- }
80
- /**
81
- * Global error handling middleware with enhanced features.
82
- *
83
- * @param {ErrorHandlerOptions} options - Error handler options
84
- * @param {boolean} [options.logErrors=true] - Whether to log errors
85
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
86
- * @returns Error middleware
87
- *
88
- * @example
89
- * import express from 'express';
90
- * import { errorHandler } from '@catbee/utils';
91
- *
92
- * const app = express();
93
- *
94
- * // Your routes
95
- * app.get('/ping', (req, res) => {
96
- * throw new Error('Something went wrong');
97
- * });
98
- *
99
- * // Error handler (must be last middleware)
100
- * app.use(errorHandler({ includeDetails: true }));
101
- *
102
- * app.listen(3000, () => {
103
- * console.log('Server running on port 3000');
104
- * });
105
- */
106
- export declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
107
- /**
108
- * Health check middleware for service status and custom checks.
109
- *
110
- * @param {object} [options] - Health check options
111
- * @param {string} [options.path='/healthz'] - Health check endpoint path
112
- * @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks
113
- * @param {boolean} [options.detailed=true] - Show detailed check results
114
- * @returns {Middleware} Express-compatible middleware
115
- */
116
- export declare function healthCheck(options?: {
117
- path?: string;
118
- checks?: Array<{
119
- name: string;
120
- check: () => Promise<boolean> | boolean;
121
- }>;
122
- detailed?: boolean;
123
- }): Middleware;
package/obj/index.cjs DELETED
@@ -1,317 +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
- 'use strict';
26
-
27
- var __defProp = Object.defineProperty;
28
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
-
30
- // src/obj/obj.utils.ts
31
- function isObjEmpty(obj) {
32
- return !!obj && typeof obj === "object" && Object.keys(obj).length === 0;
33
- }
34
- __name(isObjEmpty, "isObjEmpty");
35
- function pick(obj, keys) {
36
- return Object.fromEntries(keys.map((key) => [
37
- key,
38
- obj[key]
39
- ]));
40
- }
41
- __name(pick, "pick");
42
- function omit(obj, keys) {
43
- return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
44
- }
45
- __name(omit, "omit");
46
- function deepObjMerge(target, ...sources) {
47
- if (!sources.length) return target;
48
- const seen = /* @__PURE__ */ new WeakMap();
49
- seen.set(target, target);
50
- for (const s of sources) {
51
- if (s && typeof s === "object") {
52
- seen.set(s, target);
53
- }
54
- }
55
- function deepClone2(value) {
56
- if (value === null || typeof value !== "object") return value;
57
- if (seen.has(value)) return seen.get(value);
58
- if (value instanceof Date) {
59
- return new Date(value.getTime());
60
- }
61
- if (Array.isArray(value)) {
62
- const clone2 = [];
63
- seen.set(value, clone2);
64
- value.forEach((item, i) => clone2[i] = deepClone2(item));
65
- return clone2;
66
- }
67
- if (value instanceof Set) {
68
- const clone2 = /* @__PURE__ */ new Set();
69
- seen.set(value, clone2);
70
- value.forEach((item) => clone2.add(deepClone2(item)));
71
- return clone2;
72
- }
73
- if (value instanceof Map) {
74
- const clone2 = /* @__PURE__ */ new Map();
75
- seen.set(value, clone2);
76
- value.forEach((val, key) => clone2.set(key, deepClone2(val)));
77
- return clone2;
78
- }
79
- if (value instanceof RegExp) {
80
- return new RegExp(value.source, value.flags);
81
- }
82
- if (value instanceof ArrayBuffer) {
83
- return value.slice(0);
84
- }
85
- if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
86
- const typed = value;
87
- const ctor = typed.constructor;
88
- const typedArrayCtors = [
89
- Int8Array,
90
- Uint8Array,
91
- Uint8ClampedArray,
92
- Int16Array,
93
- Uint16Array,
94
- Int32Array,
95
- Uint32Array,
96
- Float32Array,
97
- Float64Array,
98
- BigInt64Array,
99
- BigUint64Array
100
- ].filter(Boolean);
101
- const typedArrayCtorSet = new Set(typedArrayCtors);
102
- if (typeof ctor === "function" && typedArrayCtorSet.has(ctor)) {
103
- const buffer = typed.buffer && typeof typed.buffer.slice === "function" ? typed.buffer.slice(0) : typed.buffer;
104
- const clone2 = new ctor(buffer, typed.byteOffset, typed.length);
105
- seen.set(value, clone2);
106
- return clone2;
107
- } else if (typeof typed.slice === "function") {
108
- const clone2 = typed.slice();
109
- seen.set(value, clone2);
110
- return clone2;
111
- } else {
112
- throw new Error("Cannot deep clone unknown TypedArray type: " + (typed && typed.constructor && typed.constructor.name));
113
- }
114
- }
115
- const clone = Object.create(Object.getPrototypeOf(value));
116
- seen.set(value, clone);
117
- Reflect.ownKeys(value).forEach((key) => {
118
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
119
- if (descriptor.get || descriptor.set) {
120
- Object.defineProperty(clone, key, descriptor);
121
- } else {
122
- clone[key] = deepClone2(value[key]);
123
- }
124
- });
125
- return clone;
126
- }
127
- __name(deepClone2, "deepClone");
128
- function mergeProp(target2, source, key) {
129
- const targetValue = target2[key];
130
- const sourceValue = source[key];
131
- if (sourceValue === void 0) return;
132
- if (sourceValue === null || typeof sourceValue !== "object") {
133
- target2[key] = sourceValue;
134
- return;
135
- }
136
- if (Array.isArray(sourceValue)) {
137
- target2[key] = deepClone2(sourceValue);
138
- return;
139
- }
140
- if (sourceValue instanceof Date || sourceValue instanceof RegExp || sourceValue instanceof Set || sourceValue instanceof Map || sourceValue instanceof ArrayBuffer || ArrayBuffer.isView(sourceValue) && !(sourceValue instanceof DataView)) {
141
- target2[key] = deepClone2(sourceValue);
142
- return;
143
- }
144
- if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
145
- for (const k of Reflect.ownKeys(sourceValue)) {
146
- mergeProp(targetValue, sourceValue, k);
147
- }
148
- return;
149
- }
150
- target2[key] = deepClone2(sourceValue);
151
- }
152
- __name(mergeProp, "mergeProp");
153
- for (const source of sources) {
154
- if (source == null) continue;
155
- for (const key of Reflect.ownKeys(source)) {
156
- mergeProp(target, source, key);
157
- }
158
- }
159
- return target;
160
- }
161
- __name(deepObjMerge, "deepObjMerge");
162
- function isPlainObject(value) {
163
- if (typeof value !== "object" || value === null) return false;
164
- if (Array.isArray(value)) return false;
165
- const proto = Object.getPrototypeOf(value);
166
- return proto === Object.prototype || proto === null;
167
- }
168
- __name(isPlainObject, "isPlainObject");
169
- function flattenObject(obj, prefix = "") {
170
- return Object.entries(obj).reduce((acc, [key, value]) => {
171
- const newKey = prefix ? `${prefix}.${key}` : key;
172
- if (value && typeof value === "object" && !Array.isArray(value)) {
173
- Object.assign(acc, flattenObject(value, newKey));
174
- } else {
175
- acc[newKey] = value;
176
- }
177
- return acc;
178
- }, {});
179
- }
180
- __name(flattenObject, "flattenObject");
181
- function getValueByPath(obj, path) {
182
- if (!obj || typeof obj !== "object") return void 0;
183
- const parts = path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
184
- return parts.reduce((acc, key) => acc?.[key], obj);
185
- }
186
- __name(getValueByPath, "getValueByPath");
187
- function setValueByPath(obj, path, value) {
188
- if (!obj || typeof obj !== "object") return obj;
189
- const parts = path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
190
- if (parts.length === 0) return obj;
191
- const forbiddenKeys = /* @__PURE__ */ new Set([
192
- "__proto__",
193
- "prototype",
194
- "constructor"
195
- ]);
196
- let current = obj;
197
- for (let i = 0; i < parts.length - 1; i++) {
198
- const key = parts[i];
199
- if (forbiddenKeys.has(key)) {
200
- return obj;
201
- }
202
- const nextKey = parts[i + 1];
203
- const isArrayIndex = !isNaN(Number(nextKey));
204
- if (current[key] === void 0) {
205
- current[key] = isArrayIndex ? [] : /* @__PURE__ */ Object.create(null);
206
- } else if (typeof current[key] !== "object" || current[key] === null) {
207
- current[key] = isArrayIndex ? [] : /* @__PURE__ */ Object.create(null);
208
- }
209
- current = current[key];
210
- }
211
- const finalKey = parts[parts.length - 1];
212
- if (forbiddenKeys.has(finalKey)) {
213
- return obj;
214
- }
215
- current[finalKey] = value;
216
- return obj;
217
- }
218
- __name(setValueByPath, "setValueByPath");
219
- function isEqual(a, b) {
220
- if (a === b) return true;
221
- if (a == null || b == null || typeof a !== "object" || typeof b !== "object") {
222
- return false;
223
- }
224
- if (a instanceof Date && b instanceof Date) {
225
- return a.getTime() === b.getTime();
226
- }
227
- if (a instanceof Date || b instanceof Date) {
228
- return false;
229
- }
230
- if (Array.isArray(a) && Array.isArray(b)) {
231
- if (a.length !== b.length) return false;
232
- for (let i = 0; i < a.length; i++) {
233
- if (!isEqual(a[i], b[i])) return false;
234
- }
235
- return true;
236
- }
237
- if (Array.isArray(a) || Array.isArray(b)) {
238
- return false;
239
- }
240
- const keysA = Object.keys(a);
241
- const keysB = Object.keys(b);
242
- if (keysA.length !== keysB.length) return false;
243
- return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
244
- }
245
- __name(isEqual, "isEqual");
246
- function filterObject(obj, predicate) {
247
- return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj)));
248
- }
249
- __name(filterObject, "filterObject");
250
- function mapObject(obj, mapFn) {
251
- return Object.fromEntries(Object.entries(obj).map(([key, value]) => [
252
- key,
253
- mapFn(value, key, obj)
254
- ]));
255
- }
256
- __name(mapObject, "mapObject");
257
- function deepClone(value) {
258
- try {
259
- if (typeof globalThis.structuredClone === "function") {
260
- return globalThis.structuredClone(value);
261
- }
262
- } catch (_) {
263
- }
264
- try {
265
- return JSON.parse(JSON.stringify(value));
266
- } catch (_) {
267
- return value;
268
- }
269
- }
270
- __name(deepClone, "deepClone");
271
- function deepFreeze(obj) {
272
- Object.freeze(obj);
273
- for (const prop of Object.getOwnPropertyNames(obj)) {
274
- const value = obj[prop];
275
- if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
276
- deepFreeze(value);
277
- }
278
- }
279
- return obj;
280
- }
281
- __name(deepFreeze, "deepFreeze");
282
- function isObject(value) {
283
- return value !== null && typeof value === "object" && !Array.isArray(value);
284
- }
285
- __name(isObject, "isObject");
286
- function getAllPaths(obj, parentPath = "") {
287
- if (!isObject(obj)) return [];
288
- return Object.entries(obj).flatMap(([key, value]) => {
289
- const currentPath = parentPath ? `${parentPath}.${key}` : key;
290
- if (isObject(value)) {
291
- return [
292
- currentPath,
293
- ...getAllPaths(value, currentPath)
294
- ];
295
- }
296
- return [
297
- currentPath
298
- ];
299
- });
300
- }
301
- __name(getAllPaths, "getAllPaths");
302
-
303
- exports.deepClone = deepClone;
304
- exports.deepFreeze = deepFreeze;
305
- exports.deepObjMerge = deepObjMerge;
306
- exports.filterObject = filterObject;
307
- exports.flattenObject = flattenObject;
308
- exports.getAllPaths = getAllPaths;
309
- exports.getValueByPath = getValueByPath;
310
- exports.isEqual = isEqual;
311
- exports.isObjEmpty = isObjEmpty;
312
- exports.isObject = isObject;
313
- exports.isPlainObject = isPlainObject;
314
- exports.mapObject = mapObject;
315
- exports.omit = omit;
316
- exports.pick = pick;
317
- exports.setValueByPath = setValueByPath;
package/obj/index.d.ts DELETED
@@ -1,25 +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
- export * from './obj.utils';