@catbee/utils 1.1.0 → 2.0.0-next.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 (121) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +27 -27
  3. package/array/array.utils.d.ts +191 -0
  4. package/array/index.cjs +246 -0
  5. package/array/index.d.ts +25 -0
  6. package/array/index.mjs +228 -0
  7. package/async/async.utils.d.ts +296 -0
  8. package/async/index.cjs +428 -0
  9. package/async/index.d.ts +25 -0
  10. package/async/index.mjs +407 -0
  11. package/cache/cache.utils.d.ts +176 -0
  12. package/cache/index.cjs +292 -0
  13. package/cache/index.d.ts +25 -0
  14. package/cache/index.mjs +290 -0
  15. package/config/config.d.ts +57 -0
  16. package/config/index.cjs +136 -0
  17. package/config/index.d.ts +26 -0
  18. package/config/index.mjs +131 -0
  19. package/context-store/context-store.utils.d.ts +212 -0
  20. package/context-store/index.cjs +267 -0
  21. package/context-store/index.d.ts +25 -0
  22. package/context-store/index.mjs +261 -0
  23. package/crypto/crypto.utils.d.ts +183 -0
  24. package/crypto/index.cjs +182 -0
  25. package/crypto/index.d.ts +25 -0
  26. package/crypto/index.mjs +166 -0
  27. package/date/date.utils.d.ts +190 -0
  28. package/date/index.cjs +295 -0
  29. package/date/index.d.ts +25 -0
  30. package/date/index.mjs +283 -0
  31. package/decorators/decorators.utils.d.ts +705 -0
  32. package/decorators/index.cjs +913 -0
  33. package/decorators/index.d.ts +25 -0
  34. package/decorators/index.mjs +872 -0
  35. package/dir/dir.utils.d.ts +216 -0
  36. package/dir/index.cjs +416 -0
  37. package/dir/index.d.ts +25 -0
  38. package/dir/index.mjs +389 -0
  39. package/env/env.utils.d.ts +400 -0
  40. package/env/index.cjs +761 -0
  41. package/env/index.d.ts +25 -0
  42. package/env/index.mjs +758 -0
  43. package/exception/exception.utils.d.ts +253 -0
  44. package/exception/index.cjs +362 -0
  45. package/exception/index.d.ts +25 -0
  46. package/exception/index.mjs +338 -0
  47. package/fs/fs.utils.d.ts +196 -0
  48. package/fs/index.cjs +253 -0
  49. package/fs/index.d.ts +25 -0
  50. package/fs/index.mjs +228 -0
  51. package/http-status-codes/http-status-codes.d.ts +289 -0
  52. package/http-status-codes/index.cjs +96 -0
  53. package/http-status-codes/index.d.ts +25 -0
  54. package/http-status-codes/index.mjs +94 -0
  55. package/id/id.utils.d.ts +59 -0
  56. package/id/index.cjs +62 -0
  57. package/id/index.d.ts +25 -0
  58. package/id/index.mjs +56 -0
  59. package/index.cjs +218 -0
  60. package/index.d.ts +51 -0
  61. package/index.mjs +51 -0
  62. package/logger/index.cjs +334 -0
  63. package/logger/index.d.ts +25 -0
  64. package/logger/index.mjs +313 -0
  65. package/logger/logger.utils.d.ts +210 -0
  66. package/middleware/index.cjs +177 -0
  67. package/middleware/index.d.ts +25 -0
  68. package/middleware/index.mjs +170 -0
  69. package/middleware/middleware.utils.d.ts +123 -0
  70. package/obj/index.cjs +317 -0
  71. package/obj/index.d.ts +25 -0
  72. package/obj/index.mjs +301 -0
  73. package/obj/obj.utils.d.ts +156 -0
  74. package/package.json +171 -19
  75. package/performance/index.cjs +231 -0
  76. package/performance/index.d.ts +25 -0
  77. package/performance/index.mjs +225 -0
  78. package/performance/performance.utils.d.ts +159 -0
  79. package/request/index.cjs +202 -0
  80. package/request/index.d.ts +26 -0
  81. package/request/index.mjs +194 -0
  82. package/request/request.utils.d.ts +109 -0
  83. package/response/index.cjs +234 -0
  84. package/response/index.d.ts +26 -0
  85. package/response/index.mjs +222 -0
  86. package/response/response.utils.d.ts +186 -0
  87. package/server/index.cjs +1627 -0
  88. package/server/index.d.ts +28 -0
  89. package/server/index.mjs +1617 -0
  90. package/server/server.builder.d.ts +531 -0
  91. package/server/server.d.ts +303 -0
  92. package/stream/index.cjs +151 -0
  93. package/stream/index.d.ts +25 -0
  94. package/stream/index.mjs +144 -0
  95. package/stream/stream.utils.d.ts +111 -0
  96. package/string/index.cjs +109 -0
  97. package/string/index.d.ts +25 -0
  98. package/string/index.mjs +95 -0
  99. package/string/string.utils.d.ts +124 -0
  100. package/type/index.cjs +129 -0
  101. package/type/index.d.ts +25 -0
  102. package/type/index.mjs +119 -0
  103. package/type/type.utils.d.ts +129 -0
  104. package/types/api-response.d.ts +175 -0
  105. package/types/common.d.ts +148 -0
  106. package/types/config.d.ts +88 -0
  107. package/types/index.cjs +34 -0
  108. package/types/index.d.ts +28 -0
  109. package/types/index.mjs +32 -0
  110. package/types/server.d.ts +291 -0
  111. package/url/index.cjs +201 -0
  112. package/url/index.d.ts +25 -0
  113. package/url/index.mjs +189 -0
  114. package/url/url.utils.d.ts +164 -0
  115. package/validate/index.cjs +212 -0
  116. package/validate/index.d.ts +25 -0
  117. package/validate/index.mjs +188 -0
  118. package/validate/validate.utils.d.ts +200 -0
  119. package/build/index.cjs +0 -7694
  120. package/build/index.d.ts +0 -5792
  121. package/build/index.mjs +0 -7386
@@ -0,0 +1,28 @@
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 './common';
26
+ export * from './server';
27
+ export * from './api-response';
28
+ export * from './config';
@@ -0,0 +1,32 @@
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
+ // src/types/api-response.ts
26
+ var SortDirection = /* @__PURE__ */ (function(SortDirection2) {
27
+ SortDirection2["ASC"] = "asc";
28
+ SortDirection2["DESC"] = "desc";
29
+ return SortDirection2;
30
+ })({});
31
+
32
+ export { SortDirection };
@@ -0,0 +1,291 @@
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 { Express, json, NextFunction, urlencoded, Request, Response } from 'express';
26
+ import type { ExpressServer } from '@catbee/utils/server';
27
+ import type { HelmetOptions } from 'helmet';
28
+ import type { CompressionOptions } from 'compression';
29
+ import type { CookieParseOptions } from 'cookie-parser';
30
+ import type { CorsOptions } from 'cors';
31
+ import type http from 'http';
32
+ import type { ToggleConfig } from './common';
33
+ /**
34
+ * Server configuration interface with smart defaults and full customization.
35
+ * All options are designed with security and performance best practices.
36
+ * Most options can be overridden via environment variables.
37
+ */
38
+ export interface ServerConfig {
39
+ /** Port the server should listen on (default: 3000, env: PORT)
40
+ * - default: 3000
41
+ */
42
+ port: number;
43
+ /** Optional host address for binding (default: '0.0.0.0', env: HOST)
44
+ * - default: '0.0.0.0'
45
+ */
46
+ host?: string;
47
+ /** CORS configuration (default: false disables CORS, or provide options object)
48
+ * - default: false
49
+ */
50
+ cors?: ToggleConfig<CorsOptions>;
51
+ /** Enable Helmet security headers (default: false disables Helmet, or provide options object)
52
+ * - default: false
53
+ */
54
+ helmet?: ToggleConfig<HelmetOptions>;
55
+ /** Enable gzip/deflate compression (default: false disables compression, or provide options object)
56
+ * - default: false
57
+ */
58
+ compression?: ToggleConfig<CompressionOptions>;
59
+ /** Request body parsing with size limits
60
+ * - json: { limit: '1mb' }
61
+ * - urlencoded: { extended: true, limit: '1mb' }
62
+ */
63
+ bodyParser?: {
64
+ /** JSON parser (default: { limit: '1mb' }) */
65
+ json?: Parameters<typeof json>[0];
66
+ /** URL-encoded parser (default: { extended: true, limit: '1mb' }) */
67
+ urlencoded?: Parameters<typeof urlencoded>[0];
68
+ };
69
+ /** Enable cookie parsing with options (default: false)
70
+ * - default: false
71
+ */
72
+ cookieParser?: ToggleConfig<CookieParseOptions>;
73
+ /** Trust proxy headers (default: false)
74
+ * - default: false
75
+ */
76
+ trustProxy?: boolean;
77
+ /** Static file serving configuration for assets, uploads, etc.
78
+ * - path: file system path to serve
79
+ * - route: URL route prefix (default: "/")
80
+ * - maxAge: cache max age (default: 0)
81
+ * - etag: enable ETag headers (default: true)
82
+ * - immutable: enable immutable caching (default: false)
83
+ * - lastModified: enable last-modified caching (default: true)
84
+ * - cacheControl: enable Cache-Control headers (default: true)
85
+ */
86
+ staticFolders?: Array<{
87
+ /** URL route prefix (default: "/") */
88
+ path?: string;
89
+ /** File system path to serve */
90
+ directory: string;
91
+ /** Cache-Control: max-age=<duration> (default: 0) */
92
+ maxAge?: string;
93
+ /** Enable ETag headers (default: true) */
94
+ etag?: boolean;
95
+ /** Enable immutable caching (default: false) */
96
+ immutable?: boolean;
97
+ /** Enable last-modified caching (default: true) */
98
+ lastModified?: boolean;
99
+ /** Enable Cache-Control headers (default: true) */
100
+ cacheControl?: boolean;
101
+ }>;
102
+ /** Enable microservice mode (default: false)
103
+ * - default: false
104
+ */
105
+ isMicroservice?: boolean;
106
+ /** Service name for headers/metrics (default: 'express_app', env: APP_NAME)
107
+ * - default: 'express_app'
108
+ */
109
+ appName?: string;
110
+ /** Global response headers (default: {})
111
+ * - default: {}
112
+ */
113
+ globalHeaders?: Record<string, string | (() => string)>;
114
+ /** Rate limiting settings
115
+ * - enable: false
116
+ * - windowMs: 15 * 60 * 1000
117
+ * - max: 100
118
+ * - message: 'Too many requests'
119
+ * - standardHeaders: true
120
+ * - legacyHeaders: false
121
+ */
122
+ rateLimit?: {
123
+ /** Enable rate limiting (default: false) */
124
+ enable: boolean;
125
+ /** Time window in ms (default: 900000 - 15 minutes) */
126
+ windowMs?: number;
127
+ /** Max requests per window (default: 100) */
128
+ max?: number;
129
+ /** Rate limit message (default: 'Too many requests') */
130
+ message?: string;
131
+ /** Add standard headers (default: true) */
132
+ standardHeaders?: boolean;
133
+ /** Add legacy headers (default: false) */
134
+ legacyHeaders?: boolean;
135
+ };
136
+ /** Request logging configuration
137
+ * - enable: true in dev, false in prod
138
+ * - ignorePaths: skips /healthz, /favicon.ico, /metrics, /docs, /.well-known
139
+ * - skipNotFoundRoutes: false
140
+ */
141
+ requestLogging?: {
142
+ /** Enable request logging (default: true in dev, false in prod) */
143
+ enable: boolean;
144
+ /** Ignore paths function or string[] (default: skips /healthz, /favicon.ico, /metrics, /docs, /.well-known) */
145
+ ignorePaths?: string[] | ((req: Request, res: Response) => boolean);
146
+ /** Skip logging for not found routes (default: false) */
147
+ skipNotFoundRoutes?: boolean;
148
+ };
149
+ /** Health check settings
150
+ * - path: '/healthz'
151
+ * - detailed: true
152
+ * - withGlobalPrefix: false
153
+ */
154
+ healthCheck?: {
155
+ /** Health check path (default: '/healthz') */
156
+ path?: string;
157
+ /** Custom checks (default: []) */
158
+ checks?: Array<{
159
+ name: string;
160
+ check: () => Promise<boolean> | boolean;
161
+ }>;
162
+ /** Show detailed checks status in response (default: true) */
163
+ detailed?: boolean;
164
+ /** Include in global prefix (default: false) */
165
+ withGlobalPrefix?: boolean;
166
+ };
167
+ /** Request timeout in ms (default: 30000 - 30 seconds)
168
+ * - default: 30000
169
+ */
170
+ requestTimeout?: number;
171
+ /** Response timing configuration
172
+ * - enable: false
173
+ * - addHeader: true
174
+ * - logOnComplete: false
175
+ */
176
+ responseTime?: {
177
+ /** Enable timing (default: false) */
178
+ enable: boolean;
179
+ /** Add X-Response-Time header (default: true) */
180
+ addHeader?: boolean;
181
+ /** Log completion time (default: false) */
182
+ logOnComplete?: boolean;
183
+ };
184
+ /** Request ID configuration
185
+ * - headerName: 'x-request-id'
186
+ * - exposeHeader: true
187
+ * - generator: uuid()
188
+ */
189
+ requestId?: {
190
+ /** Header name (default: 'x-request-id') */
191
+ headerName?: string;
192
+ /** Add to response headers (default: true) */
193
+ exposeHeader?: boolean;
194
+ /** ID generator (default: uuid()) */
195
+ generator?: () => string;
196
+ };
197
+ /** Global route prefix (default: '/')
198
+ * - default: '/'
199
+ */
200
+ globalPrefix?: string;
201
+ /** OpenAPI documentation
202
+ * - enable: false
203
+ * - mountPath: '/docs'
204
+ * - verbose: false
205
+ * - withGlobalPrefix: false
206
+ */
207
+ openApi?: {
208
+ /** Enable docs (default: false) */
209
+ enable: boolean;
210
+ /** UI path (default: '/docs') */
211
+ mountPath?: string;
212
+ /** Spec file path (required if enabled) */
213
+ filePath?: string;
214
+ /** Enable verbose logs (default: false) */
215
+ verbose?: boolean;
216
+ /** Include in global prefix (default: false) */
217
+ withGlobalPrefix?: boolean;
218
+ };
219
+ /** Prometheus metrics
220
+ * - enable: false
221
+ * - path: '/metrics'
222
+ * - withGlobalPrefix: false
223
+ */
224
+ metrics?: {
225
+ /** Enable metrics (default: false) */
226
+ enable: boolean;
227
+ /** Metrics path (default: '/metrics') */
228
+ path?: string;
229
+ /** Include in global prefix (default: false) */
230
+ withGlobalPrefix?: boolean;
231
+ };
232
+ /** Service version header
233
+ * - enable: false
234
+ * - headerName: 'x-service-version'
235
+ * - version: '0.0.0'
236
+ */
237
+ serviceVersion?: {
238
+ /** Enable version header (default: false) */
239
+ enable: boolean;
240
+ /** Header name (default: 'x-service-version') */
241
+ headerName?: string;
242
+ /** Version value (default: '0.0.0') */
243
+ version?: string | (() => string);
244
+ };
245
+ /**
246
+ * HTTPS configuration (if provided, server will use HTTPS)
247
+ * Requires 'key' and 'cert' at minimum.
248
+ * @command - to generate self-signed certificates
249
+ * ```bash
250
+ * choco install mkcert
251
+ * mkcert -key-file localhost-key.pem -cert-file localhost-cert.pem localhost 127.0.0.1 ::1
252
+ * ```
253
+ */
254
+ https?: {
255
+ /** Path to SSL private key file (PEM) */
256
+ key: string;
257
+ /** Path to SSL certificate file (PEM) */
258
+ cert: string;
259
+ /** Optional path to CA bundle file (PEM) */
260
+ ca?: string;
261
+ /** Optional passphrase for the private key */
262
+ passphrase?: string;
263
+ /** Any other https.ServerOptions */
264
+ [key: string]: any;
265
+ };
266
+ }
267
+ /**
268
+ * Server lifecycle hooks for custom behavior injection.
269
+ * Allows extending server functionality without modifying core code.
270
+ * All hooks can be async and support error handling.
271
+ */
272
+ export interface ServerHooks {
273
+ /** Called before any middleware or routes are initialized - good for early setup */
274
+ beforeInit?: (server: ExpressServer) => Promise<void> | void;
275
+ /** Called after middleware and routes are set up - good for final configuration */
276
+ afterInit?: (server: ExpressServer) => Promise<void> | void;
277
+ /** Called just before the server starts listening - good for last-minute checks */
278
+ beforeStart?: (app: Express) => Promise<void> | void;
279
+ /** Called after the server starts successfully - good for announcing readiness */
280
+ afterStart?: (server: http.Server) => Promise<void> | void;
281
+ /** Called before graceful shutdown begins - good for cleanup preparation */
282
+ beforeStop?: (server: http.Server) => Promise<void> | void;
283
+ /** Called after server has stopped - good for final cleanup */
284
+ afterStop?: () => Promise<void> | void;
285
+ /** Custom global error handler - overrides the default error handling */
286
+ onError?: (error: Error, req: Request, res: Response, next: NextFunction) => void;
287
+ /** Called at the start of each request - good for request preprocessing */
288
+ onRequest?: (req: Request, res: Response, next: NextFunction) => void;
289
+ /** Called before response is sent - good for response modification */
290
+ onResponse?: (req: Request, res: Response, next: NextFunction) => void;
291
+ }
package/url/index.cjs ADDED
@@ -0,0 +1,201 @@
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 url = require('url');
28
+
29
+ var __defProp = Object.defineProperty;
30
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
31
+ function appendQueryParams(url$1, params) {
32
+ const urlObj = new url.URL(url$1);
33
+ for (const [key, value] of Object.entries(params)) {
34
+ urlObj.searchParams.set(key, value.toString());
35
+ }
36
+ return urlObj.toString();
37
+ }
38
+ __name(appendQueryParams, "appendQueryParams");
39
+ function parseQueryString(query) {
40
+ const cleanQuery = query.startsWith("?") ? query.slice(1) : query;
41
+ return Object.fromEntries(new url.URLSearchParams(cleanQuery));
42
+ }
43
+ __name(parseQueryString, "parseQueryString");
44
+ function isValidUrl(url$1, requireHttps = false) {
45
+ try {
46
+ const parsedUrl = new url.URL(url$1);
47
+ if (!parsedUrl.protocol || !parsedUrl.hostname) return false;
48
+ if (requireHttps && parsedUrl.protocol !== "https:") return false;
49
+ return true;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+ __name(isValidUrl, "isValidUrl");
55
+ function getDomain(url$1, removeSubdomains = false) {
56
+ try {
57
+ const { hostname } = new url.URL(url$1);
58
+ if (!removeSubdomains) {
59
+ return hostname;
60
+ }
61
+ const parts = hostname.split(".");
62
+ if (parts.length <= 2) return hostname;
63
+ const secondLevelDomains = [
64
+ "co",
65
+ "com",
66
+ "org",
67
+ "net",
68
+ "gov",
69
+ "edu",
70
+ "ac"
71
+ ];
72
+ const sld = parts[parts.length - 2];
73
+ if (secondLevelDomains.includes(sld) && parts.length > 2) {
74
+ return parts.slice(-3).join(".");
75
+ }
76
+ return parts.slice(-2).join(".");
77
+ } catch {
78
+ return "";
79
+ }
80
+ }
81
+ __name(getDomain, "getDomain");
82
+ function joinPaths(...segments) {
83
+ let result = segments.filter((s) => s !== void 0 && s !== null).map((segment, index) => {
84
+ if (index === 0) return segment.replace(/\/+$/, "");
85
+ return segment.replace(/^\/+|\/+$/g, "");
86
+ }).filter(Boolean).join("/");
87
+ if (segments[0] === "" && !result.startsWith("/")) result = "/" + result;
88
+ return result;
89
+ }
90
+ __name(joinPaths, "joinPaths");
91
+ function normalizeUrl(url$1, base) {
92
+ try {
93
+ if (url$1.startsWith("//")) {
94
+ url$1 = `https:${url$1}`;
95
+ }
96
+ const parsedUrl = base ? new url.URL(url$1, base) : new url.URL(url$1);
97
+ parsedUrl.pathname = parsedUrl.pathname.replace(/\/+/g, "/");
98
+ parsedUrl.pathname = parsedUrl.pathname.replace(/\/+$/, "");
99
+ parsedUrl.hostname = parsedUrl.hostname.toLowerCase();
100
+ return parsedUrl.toString();
101
+ } catch {
102
+ return url$1;
103
+ }
104
+ }
105
+ __name(normalizeUrl, "normalizeUrl");
106
+ function createUrlBuilder(baseUrl) {
107
+ return {
108
+ /**
109
+ * Creates a full URL with the given path and query parameters.
110
+ *
111
+ * @param {string} path - The path to append to the base URL.
112
+ * @param {Record<string, any>} [params] - Query parameters to add.
113
+ * @returns {string} The complete URL.
114
+ */
115
+ path(path, params) {
116
+ const url = joinPaths(baseUrl, path);
117
+ return params ? appendQueryParams(url, params) : url;
118
+ },
119
+ /**
120
+ * Creates a full URL with query parameters but no additional path.
121
+ *
122
+ * @param {Record<string, any>} params - Query parameters to add.
123
+ * @returns {string} The complete URL with query parameters.
124
+ */
125
+ query(params) {
126
+ return appendQueryParams(baseUrl, params);
127
+ }
128
+ };
129
+ }
130
+ __name(createUrlBuilder, "createUrlBuilder");
131
+ function extractQueryParams(url$1, paramNames) {
132
+ try {
133
+ const parsedUrl = new url.URL(url$1);
134
+ const result = {};
135
+ for (const name of paramNames) {
136
+ const value = parsedUrl.searchParams.get(name);
137
+ if (value !== null) {
138
+ result[name] = value;
139
+ }
140
+ }
141
+ return result;
142
+ } catch {
143
+ return {};
144
+ }
145
+ }
146
+ __name(extractQueryParams, "extractQueryParams");
147
+ function removeQueryParams(url$1, paramsToRemove) {
148
+ try {
149
+ const parsedUrl = new url.URL(url$1);
150
+ for (const param of paramsToRemove) {
151
+ parsedUrl.searchParams.delete(param);
152
+ }
153
+ return parsedUrl.toString();
154
+ } catch {
155
+ return url$1;
156
+ }
157
+ }
158
+ __name(removeQueryParams, "removeQueryParams");
159
+ function getExtension(url$1) {
160
+ try {
161
+ const { pathname } = new url.URL(url$1);
162
+ const match = pathname.match(/\.([^./\\?#]+)$/);
163
+ return match ? match[1].toLowerCase() : "";
164
+ } catch {
165
+ const match = url$1.match(/\.([^./\\?#]+)$/);
166
+ return match ? match[1].toLowerCase() : "";
167
+ }
168
+ }
169
+ __name(getExtension, "getExtension");
170
+ function parseTypedQueryParams(url$1, converters) {
171
+ try {
172
+ const { searchParams } = new url.URL(url$1);
173
+ const result = {};
174
+ for (const [key, value] of searchParams.entries()) {
175
+ if (converters && key in converters) {
176
+ try {
177
+ result[key] = converters[key](value);
178
+ } catch {
179
+ }
180
+ } else {
181
+ result[key] = value;
182
+ }
183
+ }
184
+ return result;
185
+ } catch {
186
+ return {};
187
+ }
188
+ }
189
+ __name(parseTypedQueryParams, "parseTypedQueryParams");
190
+
191
+ exports.appendQueryParams = appendQueryParams;
192
+ exports.createUrlBuilder = createUrlBuilder;
193
+ exports.extractQueryParams = extractQueryParams;
194
+ exports.getDomain = getDomain;
195
+ exports.getExtension = getExtension;
196
+ exports.isValidUrl = isValidUrl;
197
+ exports.joinPaths = joinPaths;
198
+ exports.normalizeUrl = normalizeUrl;
199
+ exports.parseQueryString = parseQueryString;
200
+ exports.parseTypedQueryParams = parseTypedQueryParams;
201
+ exports.removeQueryParams = removeQueryParams;
package/url/index.d.ts ADDED
@@ -0,0 +1,25 @@
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 './url.utils';