@itshackers/utilix 0.0.0-stage → 0.3.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.
- package/LICENSE +21 -0
- package/README.md +304 -3
- package/dist/common/index.cjs +102 -0
- package/dist/common/index.cjs.map +1 -0
- package/dist/common/index.d.cts +58 -0
- package/dist/common/index.d.ts +58 -0
- package/dist/common/index.js +93 -0
- package/dist/common/index.js.map +1 -0
- package/dist/date/index.cjs +154 -0
- package/dist/date/index.cjs.map +1 -0
- package/dist/date/index.d.cts +65 -0
- package/dist/date/index.d.ts +65 -0
- package/dist/date/index.js +146 -0
- package/dist/date/index.js.map +1 -0
- package/dist/format/index.cjs +136 -0
- package/dist/format/index.cjs.map +1 -0
- package/dist/format/index.d.cts +56 -0
- package/dist/format/index.d.ts +56 -0
- package/dist/format/index.js +130 -0
- package/dist/format/index.js.map +1 -0
- package/dist/id/index.cjs +66 -0
- package/dist/id/index.cjs.map +1 -0
- package/dist/id/index.d.cts +19 -0
- package/dist/id/index.d.ts +19 -0
- package/dist/id/index.js +64 -0
- package/dist/id/index.js.map +1 -0
- package/dist/index.cjs +906 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +853 -0
- package/dist/index.js.map +1 -0
- package/dist/number/index.cjs +107 -0
- package/dist/number/index.cjs.map +1 -0
- package/dist/number/index.d.cts +90 -0
- package/dist/number/index.d.ts +90 -0
- package/dist/number/index.js +99 -0
- package/dist/number/index.js.map +1 -0
- package/dist/password/index.cjs +71 -0
- package/dist/password/index.cjs.map +1 -0
- package/dist/password/index.d.cts +15 -0
- package/dist/password/index.d.ts +15 -0
- package/dist/password/index.js +69 -0
- package/dist/password/index.js.map +1 -0
- package/dist/phone/index.cjs +19 -0
- package/dist/phone/index.cjs.map +1 -0
- package/dist/phone/index.d.cts +12 -0
- package/dist/phone/index.d.ts +12 -0
- package/dist/phone/index.js +17 -0
- package/dist/phone/index.js.map +1 -0
- package/dist/regex/index.cjs +73 -0
- package/dist/regex/index.cjs.map +1 -0
- package/dist/regex/index.d.cts +65 -0
- package/dist/regex/index.d.ts +65 -0
- package/dist/regex/index.js +67 -0
- package/dist/regex/index.js.map +1 -0
- package/dist/response/index.cjs +43 -0
- package/dist/response/index.cjs.map +1 -0
- package/dist/response/index.d.cts +41 -0
- package/dist/response/index.d.ts +41 -0
- package/dist/response/index.js +40 -0
- package/dist/response/index.js.map +1 -0
- package/dist/sanitize/index.cjs +83 -0
- package/dist/sanitize/index.cjs.map +1 -0
- package/dist/sanitize/index.d.cts +20 -0
- package/dist/sanitize/index.d.ts +20 -0
- package/dist/sanitize/index.js +80 -0
- package/dist/sanitize/index.js.map +1 -0
- package/dist/slug/index.cjs +33 -0
- package/dist/slug/index.cjs.map +1 -0
- package/dist/slug/index.d.cts +38 -0
- package/dist/slug/index.d.ts +38 -0
- package/dist/slug/index.js +31 -0
- package/dist/slug/index.js.map +1 -0
- package/dist/string/index.cjs +130 -0
- package/dist/string/index.cjs.map +1 -0
- package/dist/string/index.d.cts +112 -0
- package/dist/string/index.d.ts +112 -0
- package/dist/string/index.js +115 -0
- package/dist/string/index.js.map +1 -0
- package/package.json +187 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Its Hacker
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,304 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @itshackers/utilix
|
|
2
|
+
|
|
3
|
+
Framework-independent TypeScript utilities for frontend and backend apps. The package has no runtime dependencies and ships ESM, CommonJS, and generated `.d.ts` files.
|
|
4
|
+
|
|
5
|
+
This `README.md` is the file GitHub and npm both show. They are not different files unless you publish a separate one. Keep this document as the single source of truth.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @itshackers/utilix
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Until it is published:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pnpm add @itshackers/utilix@file:../utilix
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Node.js 18+ and modern browsers are supported. The compiled code does not use Node built-ins.
|
|
20
|
+
|
|
21
|
+
## Run the project
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
cd utilix
|
|
25
|
+
pnpm install
|
|
26
|
+
pnpm test
|
|
27
|
+
pnpm typecheck
|
|
28
|
+
pnpm build
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| Command | Purpose |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| `pnpm test` | Run unit tests once |
|
|
34
|
+
| `pnpm test:watch` | Re-run tests on change |
|
|
35
|
+
| `pnpm typecheck` | Strict TypeScript check |
|
|
36
|
+
| `pnpm build` | Clean ESM + CJS + declaration build |
|
|
37
|
+
| `pnpm dev` | Watch-mode build |
|
|
38
|
+
| `pnpm prepublishOnly` | Typecheck, test, then build |
|
|
39
|
+
|
|
40
|
+
`prepublishOnly` does not publish. See [Publish to npm](#publish-to-npm) for the first-release commands.
|
|
41
|
+
|
|
42
|
+
## Imports
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { slugify, normalizeMobile, testPattern } from "@itshackers/utilix";
|
|
46
|
+
|
|
47
|
+
import { toCamelCase } from "@itshackers/utilix/string";
|
|
48
|
+
import { toNumber } from "@itshackers/utilix/number";
|
|
49
|
+
import { slugify } from "@itshackers/utilix/slug";
|
|
50
|
+
import { omitEmpty } from "@itshackers/utilix/common";
|
|
51
|
+
import { formatPriceToLakh } from "@itshackers/utilix/format";
|
|
52
|
+
import { parseIstDateTimeToUtc } from "@itshackers/utilix/date";
|
|
53
|
+
import { normalizeMobile } from "@itshackers/utilix/phone";
|
|
54
|
+
import { generatePassword } from "@itshackers/utilix/password";
|
|
55
|
+
import { generatePrefixedCode } from "@itshackers/utilix/id";
|
|
56
|
+
import { sanitizeForLog } from "@itshackers/utilix/sanitize";
|
|
57
|
+
import { createSuccessResponse } from "@itshackers/utilix/response";
|
|
58
|
+
import { ValidationPatterns, testPattern } from "@itshackers/utilix/regex";
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
CommonJS: `require("@itshackers/utilix")` and the same subpaths.
|
|
62
|
+
|
|
63
|
+
## String — `@itshackers/utilix/string`
|
|
64
|
+
|
|
65
|
+
| Function | Example | Result |
|
|
66
|
+
| --- | --- | --- |
|
|
67
|
+
| `toCamelCase(value)` | `toCamelCase("hello-world")` | `"helloWorld"` |
|
|
68
|
+
| `toPascalCase(value)` | `toPascalCase("hello_world")` | `"HelloWorld"` |
|
|
69
|
+
| `toSnakeCase(value)` | `toSnakeCase("Hello World")` | `"hello_world"` |
|
|
70
|
+
| `toKebabCase(value)` | `toKebabCase("HelloWorld")` | `"hello-world"` |
|
|
71
|
+
| `toTitleCase(value)` | `toTitleCase("used-truck")` | `"Used-Truck"` |
|
|
72
|
+
| `convertCase(value, style?)` | `convertCase("hello-world", "camel")` | `"helloWorld"` |
|
|
73
|
+
| `capitalize(value)` | `capitalize(" hello")` | `"Hello"` |
|
|
74
|
+
| `normalizeWhitespace(value)` | `normalizeWhitespace(" a b ")` | `"a b"` |
|
|
75
|
+
| `replaceSeparatorsWithSpace(value)` | `replaceSeparatorsWithSpace("used-truck")` | `"Used Truck"` |
|
|
76
|
+
| `htmlToPlainText(value)` | `htmlToPlainText("<p>Hi<br>There</p>")` | `"Hi There"` |
|
|
77
|
+
| `nonEmptyString(value)` | `nonEmptyString(" Gold ")` | `"Gold"` |
|
|
78
|
+
| `escapeHtml(value)` | `escapeHtml("<b>")` | `"<b>"` |
|
|
79
|
+
| `escapeRegex(value)` | `escapeRegex("a.b")` | `"a\\.b"` |
|
|
80
|
+
|
|
81
|
+
`convertCase` styles: `title`, `lower`, `upper`, `camel`, `pascal`, `snake`, `kebab`, plus `*case` aliases. Unknown styles throw.
|
|
82
|
+
|
|
83
|
+
`escapeHtml` and `htmlToPlainText` are not HTML sanitizers.
|
|
84
|
+
|
|
85
|
+
## Number — `@itshackers/utilix/number`
|
|
86
|
+
|
|
87
|
+
| Function | Example | Result |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| `toNumber(value)` | `toNumber("12.5")` / `toNumber("1,234")` | `12.5` / `null` |
|
|
90
|
+
| `toNumberIfValid(value)` | `toNumberIfValid("08")` / `toNumberIfValid("gold")` | `8` / `"gold"` |
|
|
91
|
+
| `parsePositiveInt(value, fallback)` | `parsePositiveInt("0", 10)` | `10` |
|
|
92
|
+
| `formatNumber(value, options?)` | `formatNumber(1234567.89)` | `"12,34,567.89"` |
|
|
93
|
+
| `formatCurrency(value, currency?, locale?)` | `formatCurrency(1500)` | `"₹1,500.00"` |
|
|
94
|
+
| `clamp(value, min, max)` | `clamp(15, 0, 10)` | `10` |
|
|
95
|
+
| `roundTo(value, decimals?)` | `roundTo(1.2345, 2)` | `1.23` |
|
|
96
|
+
|
|
97
|
+
Defaults: locale `en-IN`, currency `INR`. `toNumber` rejects locale grouping such as `"1,234"`.
|
|
98
|
+
|
|
99
|
+
## Slug — `@itshackers/utilix/slug`
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
slugify("Cavalo Care — RSA Plans"); // "cavalo-care-rsa-plans"
|
|
103
|
+
slugify("Hello World", { separator: "_" }); // "hello_world"
|
|
104
|
+
slugify("Café Products", { preserveUnicode: false }); // "cafe-products"
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Options: `separator` (`"-"`), `maxLength`, `preserveUnicode` (`true`). Slugs are not unique and are not full transliteration.
|
|
108
|
+
|
|
109
|
+
## Common — `@itshackers/utilix/common`
|
|
110
|
+
|
|
111
|
+
| Function | Example | Result |
|
|
112
|
+
| --- | --- | --- |
|
|
113
|
+
| `isPlainObject(value)` | `isPlainObject({})` / `isPlainObject([])` | `true` / `false` |
|
|
114
|
+
| `isNilOrEmpty(value)` | `isNilOrEmpty(" ")` / `isNilOrEmpty(0)` | `true` / `false` |
|
|
115
|
+
| `coalesce(value, fallback)` | `coalesce(null, "Silver")` | `"Silver"` |
|
|
116
|
+
| `toBoolean(value, fallback?)` | `toBoolean("true")` / `toBoolean(null, true)` | `true` / `true` |
|
|
117
|
+
| `deepTrim(value)` | `deepTrim({ name: " Gold " })` | `{ name: "Gold" }` |
|
|
118
|
+
| `omitEmpty(value)` | `omitEmpty({ note: "", count: 0 })` | `{ count: 0 }` |
|
|
119
|
+
| `pickAllowed(value, allowed, fallback)` | `pickAllowed("hi", ["en", "hi"], "en")` | `"hi"` |
|
|
120
|
+
| `sleep(ms)` | `await sleep(250)` | `void` |
|
|
121
|
+
|
|
122
|
+
## Format — `@itshackers/utilix/format`
|
|
123
|
+
|
|
124
|
+
| Function | Example | Result |
|
|
125
|
+
| --- | --- | --- |
|
|
126
|
+
| `formatDateTime(value, options?)` | `formatDateTime("2024-01-15T00:00:00.000Z")` | IST date-time or `null` |
|
|
127
|
+
| `formatFileSize(bytes, decimals?)` | `formatFileSize(1536)` | `"1.5 KB"` |
|
|
128
|
+
| `formatDuration(seconds)` | `formatDuration(3661)` | `"1 hr 1 min 1 sec"` |
|
|
129
|
+
| `formatDurationCompact(value, options?)` | `formatDurationCompact(3661)` | `"1h 1m 1s"` |
|
|
130
|
+
| `formatPriceToLakh(price, decimals?)` | `formatPriceToLakh(2_000_000)` | `"20.00 Lakh"` |
|
|
131
|
+
|
|
132
|
+
`formatDateTime` defaults to `en-IN` / `Asia/Kolkata`. Months in compact durations are labeled `mo`.
|
|
133
|
+
|
|
134
|
+
## Date — `@itshackers/utilix/date`
|
|
135
|
+
|
|
136
|
+
| Function | Use |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| `parseIstDateTimeToUtc(value)` | Naive `"YYYY-MM-DD HH:mm:ss"` is treated as IST |
|
|
139
|
+
| `formatUtcToIstDateTime(value)` | UTC instant → `"YYYY-MM-DD HH:mm:ss"` IST |
|
|
140
|
+
| `getIstDateParts(date?)` | `{ year, month, day, hour }` in IST |
|
|
141
|
+
| `addCalendarDays(year, month, day, days)` | Calendar arithmetic |
|
|
142
|
+
| `istDateTime(y, m, d, h?, min?, s?, ms?)` | Build an IST `Date` |
|
|
143
|
+
| `getExpiryInfo(expiresAt, options?)` | Remaining time, `needsRefresh`, `isExpired` |
|
|
144
|
+
| `getCalendarWindow(options?)` | Configurable IST booking window |
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
parseIstDateTimeToUtc("2024-01-15 05:30:00"); // 2024-01-15T00:00:00.000Z
|
|
148
|
+
getExpiryInfo(expiresAt, { warningDays: 7, compact: true, now });
|
|
149
|
+
getCalendarWindow({ cutoffHour: 14, windowDays: 36 });
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Phone — `@itshackers/utilix/phone`
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
normalizeMobile("+91 98765 43210"); // "9876543210"
|
|
156
|
+
normalizeMobile("12345"); // null
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Indian 10-digit numbers starting with 6-9 only.
|
|
160
|
+
|
|
161
|
+
## Password — `@itshackers/utilix/password`
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
generatePassword(); // length 12
|
|
165
|
+
generatePassword(16); // minimum 8
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Uses `crypto.getRandomValues`. This generates passwords; it does not hash them. Keep bcrypt/argon2 in the app.
|
|
169
|
+
|
|
170
|
+
## ID — `@itshackers/utilix/id`
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
generatePrefixedCode({ prefix: "PLAN" });
|
|
174
|
+
generatePrefixedCode({ prefix: "SAVE", randomLength: 6, includeTimestamp: false });
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Does not guarantee uniqueness. Options: `prefix`, `randomLength`, `includeTimestamp`, `now`, `charset`.
|
|
178
|
+
|
|
179
|
+
## Sanitize — `@itshackers/utilix/sanitize`
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
sanitizeForLog({ password: "secret", name: "Gold" });
|
|
183
|
+
// { password: "[REDACTED]", name: "Gold" }
|
|
184
|
+
|
|
185
|
+
sanitizeHeaders({ Authorization: "Bearer x", "content-type": "application/json" });
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Configurable: `sensitiveKeys`, `maxDepth`, `maxString`, `maxArray`, `redactedValue`, `truncatedValue`.
|
|
189
|
+
|
|
190
|
+
## Response — `@itshackers/utilix/response`
|
|
191
|
+
|
|
192
|
+
Framework-independent payloads. These do not call Express `res.json`.
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
createSuccessResponse({
|
|
196
|
+
message: "Created",
|
|
197
|
+
data: { id: 1 },
|
|
198
|
+
requestId: "req-1",
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
createErrorResponse({
|
|
202
|
+
message: "Invalid mobile",
|
|
203
|
+
code: "VALIDATION_ERROR",
|
|
204
|
+
errors: { mobile: ["required"] },
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## Regex — `@itshackers/utilix/regex`
|
|
209
|
+
|
|
210
|
+
Shape checks only. Not official document validation.
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
ValidationPatterns.EMAIL.test("user@example.com");
|
|
214
|
+
testPattern("9876543210", "MOBILE");
|
|
215
|
+
testPattern("123456", "OTP");
|
|
216
|
+
getPattern("PINCODE");
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
| Name | Typical valid input |
|
|
220
|
+
| --- | --- |
|
|
221
|
+
| `YEAR` | `2024` |
|
|
222
|
+
| `OTP` | `123456` |
|
|
223
|
+
| `PINCODE` / `POSTAL_CODE` | `560001` |
|
|
224
|
+
| `NUMERIC` | `42` |
|
|
225
|
+
| `MOBILE` | `9876543210` |
|
|
226
|
+
| `NAME` | `Ravi Kumar` |
|
|
227
|
+
| `ALPHABETIC` | `Gold` |
|
|
228
|
+
| `LOWERCASE_ONLY` | `gold_plan` |
|
|
229
|
+
| `UPPERCASE_ONLY` | `GOLD_PLAN` |
|
|
230
|
+
| `USERNAME` | `ravi_01` |
|
|
231
|
+
| `LOWER_NUMERIC` | `plan_01` |
|
|
232
|
+
| `UPPER_NUMERIC` | `PLAN_01` |
|
|
233
|
+
| `LOWER_WITH_HYPHENS` | `gold-plan` |
|
|
234
|
+
| `UPPER_WITH_HYPHENS` | `GOLD-PLAN` |
|
|
235
|
+
| `ALPHANUMERIC` | `Gold 12` |
|
|
236
|
+
| `PERMISSION_NAME` | `leads.create` |
|
|
237
|
+
| `AADHAR_CARD` | `234567890123` |
|
|
238
|
+
| `LOWER_NUMERIC_WITH_HYPHENS` | `plan-01` |
|
|
239
|
+
| `UPPER_NUMERIC_WITH_HYPHENS` | `PLAN-01` |
|
|
240
|
+
| `ALPHANUMERIC_WITH_SPACES` | `Gold 12` |
|
|
241
|
+
| `ALPHANUMERIC_WITHOUT_SPACES` | `Gold12` |
|
|
242
|
+
| `PAN_CARD` | `ABCDE1234F` |
|
|
243
|
+
| `ALPHANUMERIC_WITH_UNDERSCORES` | `Gold_12` |
|
|
244
|
+
| `MODEL_NAME` | `Tata 407` |
|
|
245
|
+
| `NOTE` | `Follow up @ 10am` |
|
|
246
|
+
| `EMAIL` | `user@example.com` |
|
|
247
|
+
| `VEHICLE_NUMBER` | `KA01AB1234` |
|
|
248
|
+
| `PASSWORD` | `Abcd1234@` |
|
|
249
|
+
| `URL` | `https://example.com` |
|
|
250
|
+
| `DATE` | `2024-01-15` |
|
|
251
|
+
| `CURRENCY` | `1500.50` |
|
|
252
|
+
| `TIME` | `09:30` |
|
|
253
|
+
| `MESSAGE` | `Need RSA today` |
|
|
254
|
+
| `DOMAIN_HOSTNAME` | `care.example.com` |
|
|
255
|
+
|
|
256
|
+
## Limitations
|
|
257
|
+
|
|
258
|
+
- No runtime password hashing. Use bcrypt/argon2 in the application.
|
|
259
|
+
- No Express `res.status().json()` helpers. Use `createSuccessResponse` / `createErrorResponse`, then send the object yourself.
|
|
260
|
+
- `escapeHtml` / `htmlToPlainText` are not sanitizers.
|
|
261
|
+
- `toNumber` does not parse locale grouping.
|
|
262
|
+
- `slugify` and `generatePrefixedCode` do not guarantee uniqueness.
|
|
263
|
+
- `normalizeMobile` is Indian-only.
|
|
264
|
+
- Validation patterns check shape, not official validity.
|
|
265
|
+
- Duration months/years use 30-day and 365-day approximations.
|
|
266
|
+
|
|
267
|
+
## Publish to npm
|
|
268
|
+
|
|
269
|
+
Replace `OWNER/REPO` in `package.json` (`homepage`, `repository`, `bugs`) before the first release. Do not change `name` or `version` unless you intend a new identity or bump.
|
|
270
|
+
|
|
271
|
+
This package is scoped (`@itshackers/utilix`) and already has `"publishConfig": { "access": "public" }`. Create the `@itshackers` npm organization first if it does not exist, then add your user to it.
|
|
272
|
+
|
|
273
|
+
### First public release
|
|
274
|
+
|
|
275
|
+
Run these from the package root after you have an npm account that can publish `@itshackers/*`:
|
|
276
|
+
|
|
277
|
+
```bash
|
|
278
|
+
cd "D:\Its Hacker\WORK_DIR\utilix"
|
|
279
|
+
pnpm login
|
|
280
|
+
pnpm prepublishOnly
|
|
281
|
+
pnpm pack --dry-run
|
|
282
|
+
pnpm publish --access public
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
If the account uses 2FA, npm will prompt for an OTP. You can also pass it:
|
|
286
|
+
|
|
287
|
+
```bash
|
|
288
|
+
pnpm publish --access public --otp 123456
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
`pnpm publish` runs `prepublishOnly` again (typecheck, tests, production build) and does not run unless you execute it.
|
|
292
|
+
|
|
293
|
+
Inspect the tarball without publishing:
|
|
294
|
+
|
|
295
|
+
```bash
|
|
296
|
+
pnpm pack
|
|
297
|
+
tar -tzf itshackers-utilix-0.3.0.tgz
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
The published files should be `package.json`, `README.md`, `LICENSE`, and `dist/**` only.
|
|
301
|
+
|
|
302
|
+
## License
|
|
303
|
+
|
|
304
|
+
MIT
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/internal/validation.ts
|
|
4
|
+
function assertFiniteNumber(value, name) {
|
|
5
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
6
|
+
throw new TypeError(`${name} must be a finite number`);
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// src/common/index.ts
|
|
11
|
+
function isPlainObject(value) {
|
|
12
|
+
if (value === null || typeof value !== "object") {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
const prototype = Object.getPrototypeOf(value);
|
|
16
|
+
return prototype === null || prototype === Object.prototype;
|
|
17
|
+
}
|
|
18
|
+
function isNilOrEmpty(value) {
|
|
19
|
+
if (value == null) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
if (typeof value === "string") {
|
|
23
|
+
return value.trim().length === 0;
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
function coalesce(value, fallback) {
|
|
28
|
+
return value ?? fallback;
|
|
29
|
+
}
|
|
30
|
+
function toBoolean(value, fallback = false) {
|
|
31
|
+
if (value === true || value === 1 || value === "1") {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
if (value === false || value === 0 || value === "0") {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (typeof value === "string") {
|
|
38
|
+
const normalized = value.trim().toLowerCase();
|
|
39
|
+
if (normalized.length === 0) {
|
|
40
|
+
return fallback;
|
|
41
|
+
}
|
|
42
|
+
if (normalized === "true") {
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
if (normalized === "false") {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (value == null) {
|
|
50
|
+
return fallback;
|
|
51
|
+
}
|
|
52
|
+
return fallback;
|
|
53
|
+
}
|
|
54
|
+
function deepTrim(value) {
|
|
55
|
+
if (typeof value === "string") {
|
|
56
|
+
return value.trim();
|
|
57
|
+
}
|
|
58
|
+
if (Array.isArray(value)) {
|
|
59
|
+
return value.map((item) => deepTrim(item));
|
|
60
|
+
}
|
|
61
|
+
if (isPlainObject(value)) {
|
|
62
|
+
return Object.fromEntries(
|
|
63
|
+
Object.entries(value).map(([key, nested]) => [key, deepTrim(nested)])
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
function omitEmpty(value) {
|
|
69
|
+
if (!isPlainObject(value)) {
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
const cleaned = { ...value };
|
|
73
|
+
for (const key of Object.keys(cleaned)) {
|
|
74
|
+
if (cleaned[key] === "" || cleaned[key] === null) {
|
|
75
|
+
delete cleaned[key];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return cleaned;
|
|
79
|
+
}
|
|
80
|
+
function pickAllowed(value, allowed, fallback) {
|
|
81
|
+
return allowed.includes(value) ? value : fallback;
|
|
82
|
+
}
|
|
83
|
+
function sleep(milliseconds) {
|
|
84
|
+
assertFiniteNumber(milliseconds, "milliseconds");
|
|
85
|
+
if (milliseconds < 0) {
|
|
86
|
+
throw new RangeError("milliseconds must be greater than or equal to 0");
|
|
87
|
+
}
|
|
88
|
+
return new Promise((resolve) => {
|
|
89
|
+
setTimeout(resolve, milliseconds);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
exports.coalesce = coalesce;
|
|
94
|
+
exports.deepTrim = deepTrim;
|
|
95
|
+
exports.isNilOrEmpty = isNilOrEmpty;
|
|
96
|
+
exports.isPlainObject = isPlainObject;
|
|
97
|
+
exports.omitEmpty = omitEmpty;
|
|
98
|
+
exports.pickAllowed = pickAllowed;
|
|
99
|
+
exports.sleep = sleep;
|
|
100
|
+
exports.toBoolean = toBoolean;
|
|
101
|
+
//# sourceMappingURL=index.cjs.map
|
|
102
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/internal/validation.ts","../../src/common/index.ts"],"names":[],"mappings":";;;AAAO,SAAS,kBAAA,CACd,OACA,IAAA,EACyB;AACzB,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,EAAG;AACxD,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,EAAG,IAAI,CAAA,wBAAA,CAA0B,CAAA;AAAA,EACvD;AACF;;;ACAO,SAAS,cAAc,KAAA,EAAkD;AAC9E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AAA;AACvD;AAKO,SAAS,MAAM,YAAA,EAAqC;AACzD,EAAA,kBAAA,CAAmB,cAAc,cAAc,CAAA;AAE/C,EAAA,IAAI,eAAe,CAAA,EAAG;AACpB,IAAA,MAAM,IAAI,WAAW,iDAAiD,CAAA;AAAA,EACxE;AAEA,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC9B,IAAA,UAAA,CAAW,SAAS,YAAY,CAAA;AAAA,EAClC,CAAC,CAAA;AACH","file":"index.cjs","sourcesContent":["export function assertFiniteNumber(\r\n value: unknown,\r\n name: string,\r\n): asserts value is number {\r\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\r\n throw new TypeError(`${name} must be a finite number`);\r\n }\r\n}\r\n\r\nexport function escapeRegExp(value: string): string {\r\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\r\n}\r\n","import { assertFiniteNumber } from \"../internal/validation.js\";\r\n\r\n/**\r\n * Returns `true` when the value is a plain object created by `{}`,\r\n * `Object.create(null)`, or `new Object()`. Arrays, `null`, and class\r\n * instances are rejected.\r\n */\r\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\r\n if (value === null || typeof value !== \"object\") {\r\n return false;\r\n }\r\n\r\n const prototype = Object.getPrototypeOf(value);\r\n return prototype === null || prototype === Object.prototype;\r\n}\r\n\r\n/**\r\n * Returns `true` for `null`, `undefined`, and whitespace-only strings.\r\n * `0` and `false` are not treated as empty.\r\n */\r\nexport function isNilOrEmpty(value: unknown): boolean {\r\n if (value == null) {\r\n return true;\r\n }\r\n\r\n if (typeof value === \"string\") {\r\n return value.trim().length === 0;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/**\r\n * Returns `value` unless it is `null` or `undefined`, in which case\r\n * `fallback` is returned.\r\n */\r\nexport function coalesce<T>(value: T | null | undefined, fallback: T): T {\r\n return value ?? fallback;\r\n}\r\n\r\n/**\r\n * Coerces common truthy/falsey inputs to a boolean.\r\n * `null`, `undefined`, and empty or whitespace-only strings return `fallback`.\r\n *\r\n * @example\r\n * toBoolean(\"true\") // true\r\n * toBoolean(\"0\") // false\r\n * toBoolean(null, true) // true\r\n */\r\nexport function toBoolean(value: unknown, fallback = false): boolean {\r\n if (value === true || value === 1 || value === \"1\") {\r\n return true;\r\n }\r\n\r\n if (value === false || value === 0 || value === \"0\") {\r\n return false;\r\n }\r\n\r\n if (typeof value === \"string\") {\r\n const normalized = value.trim().toLowerCase();\r\n if (normalized.length === 0) {\r\n return fallback;\r\n }\r\n if (normalized === \"true\") {\r\n return true;\r\n }\r\n if (normalized === \"false\") {\r\n return false;\r\n }\r\n }\r\n\r\n if (value == null) {\r\n return fallback;\r\n }\r\n\r\n return fallback;\r\n}\r\n\r\n/**\r\n * Recursively trims strings in arrays and plain objects.\r\n * Dates, class instances, and other non-plain objects are left unchanged.\r\n *\r\n * @example\r\n * deepTrim({ name: \" Gold \", tags: [\" rsa \"] })\r\n * // { name: \"Gold\", tags: [\"rsa\"] }\r\n */\r\nexport function deepTrim<T>(value: T): T {\r\n if (typeof value === \"string\") {\r\n return value.trim() as T;\r\n }\r\n\r\n if (Array.isArray(value)) {\r\n return value.map((item) => deepTrim(item)) as T;\r\n }\r\n\r\n if (isPlainObject(value)) {\r\n return Object.fromEntries(\r\n Object.entries(value).map(([key, nested]) => [key, deepTrim(nested)]),\r\n ) as T;\r\n }\r\n\r\n return value;\r\n}\r\n\r\n/**\r\n * Returns a shallow copy of a plain object without `null` or empty-string values.\r\n * Non-plain values are returned unchanged.\r\n *\r\n * @example\r\n * omitEmpty({ name: \"Gold\", note: \"\", city: null })\r\n * // { name: \"Gold\" }\r\n */\r\nexport function omitEmpty<T>(value: T): T {\r\n if (!isPlainObject(value)) {\r\n return value;\r\n }\r\n\r\n const cleaned = { ...value };\r\n for (const key of Object.keys(cleaned)) {\r\n if (cleaned[key] === \"\" || cleaned[key] === null) {\r\n delete cleaned[key];\r\n }\r\n }\r\n\r\n return cleaned as T;\r\n}\r\n\r\n/**\r\n * Returns `value` when it is one of the allowed values, otherwise `fallback`.\r\n *\r\n * @example\r\n * pickAllowed(\"hi\", [\"en\", \"hi\"] as const, \"en\") // \"hi\"\r\n * pickAllowed(\"fr\", [\"en\", \"hi\"] as const, \"en\") // \"en\"\r\n */\r\nexport function pickAllowed<T>(\r\n value: unknown,\r\n allowed: readonly T[],\r\n fallback: T,\r\n): T {\r\n return allowed.includes(value as T) ? (value as T) : fallback;\r\n}\r\n\r\n/**\r\n * Resolves after the given number of milliseconds.\r\n */\r\nexport function sleep(milliseconds: number): Promise<void> {\r\n assertFiniteNumber(milliseconds, \"milliseconds\");\r\n\r\n if (milliseconds < 0) {\r\n throw new RangeError(\"milliseconds must be greater than or equal to 0\");\r\n }\r\n\r\n return new Promise((resolve) => {\r\n setTimeout(resolve, milliseconds);\r\n });\r\n}\r\n"]}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns `true` when the value is a plain object created by `{}`,
|
|
3
|
+
* `Object.create(null)`, or `new Object()`. Arrays, `null`, and class
|
|
4
|
+
* instances are rejected.
|
|
5
|
+
*/
|
|
6
|
+
declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
7
|
+
/**
|
|
8
|
+
* Returns `true` for `null`, `undefined`, and whitespace-only strings.
|
|
9
|
+
* `0` and `false` are not treated as empty.
|
|
10
|
+
*/
|
|
11
|
+
declare function isNilOrEmpty(value: unknown): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Returns `value` unless it is `null` or `undefined`, in which case
|
|
14
|
+
* `fallback` is returned.
|
|
15
|
+
*/
|
|
16
|
+
declare function coalesce<T>(value: T | null | undefined, fallback: T): T;
|
|
17
|
+
/**
|
|
18
|
+
* Coerces common truthy/falsey inputs to a boolean.
|
|
19
|
+
* `null`, `undefined`, and empty or whitespace-only strings return `fallback`.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* toBoolean("true") // true
|
|
23
|
+
* toBoolean("0") // false
|
|
24
|
+
* toBoolean(null, true) // true
|
|
25
|
+
*/
|
|
26
|
+
declare function toBoolean(value: unknown, fallback?: boolean): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Recursively trims strings in arrays and plain objects.
|
|
29
|
+
* Dates, class instances, and other non-plain objects are left unchanged.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* deepTrim({ name: " Gold ", tags: [" rsa "] })
|
|
33
|
+
* // { name: "Gold", tags: ["rsa"] }
|
|
34
|
+
*/
|
|
35
|
+
declare function deepTrim<T>(value: T): T;
|
|
36
|
+
/**
|
|
37
|
+
* Returns a shallow copy of a plain object without `null` or empty-string values.
|
|
38
|
+
* Non-plain values are returned unchanged.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* omitEmpty({ name: "Gold", note: "", city: null })
|
|
42
|
+
* // { name: "Gold" }
|
|
43
|
+
*/
|
|
44
|
+
declare function omitEmpty<T>(value: T): T;
|
|
45
|
+
/**
|
|
46
|
+
* Returns `value` when it is one of the allowed values, otherwise `fallback`.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* pickAllowed("hi", ["en", "hi"] as const, "en") // "hi"
|
|
50
|
+
* pickAllowed("fr", ["en", "hi"] as const, "en") // "en"
|
|
51
|
+
*/
|
|
52
|
+
declare function pickAllowed<T>(value: unknown, allowed: readonly T[], fallback: T): T;
|
|
53
|
+
/**
|
|
54
|
+
* Resolves after the given number of milliseconds.
|
|
55
|
+
*/
|
|
56
|
+
declare function sleep(milliseconds: number): Promise<void>;
|
|
57
|
+
|
|
58
|
+
export { coalesce, deepTrim, isNilOrEmpty, isPlainObject, omitEmpty, pickAllowed, sleep, toBoolean };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns `true` when the value is a plain object created by `{}`,
|
|
3
|
+
* `Object.create(null)`, or `new Object()`. Arrays, `null`, and class
|
|
4
|
+
* instances are rejected.
|
|
5
|
+
*/
|
|
6
|
+
declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
7
|
+
/**
|
|
8
|
+
* Returns `true` for `null`, `undefined`, and whitespace-only strings.
|
|
9
|
+
* `0` and `false` are not treated as empty.
|
|
10
|
+
*/
|
|
11
|
+
declare function isNilOrEmpty(value: unknown): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Returns `value` unless it is `null` or `undefined`, in which case
|
|
14
|
+
* `fallback` is returned.
|
|
15
|
+
*/
|
|
16
|
+
declare function coalesce<T>(value: T | null | undefined, fallback: T): T;
|
|
17
|
+
/**
|
|
18
|
+
* Coerces common truthy/falsey inputs to a boolean.
|
|
19
|
+
* `null`, `undefined`, and empty or whitespace-only strings return `fallback`.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* toBoolean("true") // true
|
|
23
|
+
* toBoolean("0") // false
|
|
24
|
+
* toBoolean(null, true) // true
|
|
25
|
+
*/
|
|
26
|
+
declare function toBoolean(value: unknown, fallback?: boolean): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Recursively trims strings in arrays and plain objects.
|
|
29
|
+
* Dates, class instances, and other non-plain objects are left unchanged.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* deepTrim({ name: " Gold ", tags: [" rsa "] })
|
|
33
|
+
* // { name: "Gold", tags: ["rsa"] }
|
|
34
|
+
*/
|
|
35
|
+
declare function deepTrim<T>(value: T): T;
|
|
36
|
+
/**
|
|
37
|
+
* Returns a shallow copy of a plain object without `null` or empty-string values.
|
|
38
|
+
* Non-plain values are returned unchanged.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* omitEmpty({ name: "Gold", note: "", city: null })
|
|
42
|
+
* // { name: "Gold" }
|
|
43
|
+
*/
|
|
44
|
+
declare function omitEmpty<T>(value: T): T;
|
|
45
|
+
/**
|
|
46
|
+
* Returns `value` when it is one of the allowed values, otherwise `fallback`.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* pickAllowed("hi", ["en", "hi"] as const, "en") // "hi"
|
|
50
|
+
* pickAllowed("fr", ["en", "hi"] as const, "en") // "en"
|
|
51
|
+
*/
|
|
52
|
+
declare function pickAllowed<T>(value: unknown, allowed: readonly T[], fallback: T): T;
|
|
53
|
+
/**
|
|
54
|
+
* Resolves after the given number of milliseconds.
|
|
55
|
+
*/
|
|
56
|
+
declare function sleep(milliseconds: number): Promise<void>;
|
|
57
|
+
|
|
58
|
+
export { coalesce, deepTrim, isNilOrEmpty, isPlainObject, omitEmpty, pickAllowed, sleep, toBoolean };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// src/internal/validation.ts
|
|
2
|
+
function assertFiniteNumber(value, name) {
|
|
3
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
4
|
+
throw new TypeError(`${name} must be a finite number`);
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// src/common/index.ts
|
|
9
|
+
function isPlainObject(value) {
|
|
10
|
+
if (value === null || typeof value !== "object") {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
const prototype = Object.getPrototypeOf(value);
|
|
14
|
+
return prototype === null || prototype === Object.prototype;
|
|
15
|
+
}
|
|
16
|
+
function isNilOrEmpty(value) {
|
|
17
|
+
if (value == null) {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
if (typeof value === "string") {
|
|
21
|
+
return value.trim().length === 0;
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
function coalesce(value, fallback) {
|
|
26
|
+
return value ?? fallback;
|
|
27
|
+
}
|
|
28
|
+
function toBoolean(value, fallback = false) {
|
|
29
|
+
if (value === true || value === 1 || value === "1") {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
if (value === false || value === 0 || value === "0") {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
if (typeof value === "string") {
|
|
36
|
+
const normalized = value.trim().toLowerCase();
|
|
37
|
+
if (normalized.length === 0) {
|
|
38
|
+
return fallback;
|
|
39
|
+
}
|
|
40
|
+
if (normalized === "true") {
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
if (normalized === "false") {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (value == null) {
|
|
48
|
+
return fallback;
|
|
49
|
+
}
|
|
50
|
+
return fallback;
|
|
51
|
+
}
|
|
52
|
+
function deepTrim(value) {
|
|
53
|
+
if (typeof value === "string") {
|
|
54
|
+
return value.trim();
|
|
55
|
+
}
|
|
56
|
+
if (Array.isArray(value)) {
|
|
57
|
+
return value.map((item) => deepTrim(item));
|
|
58
|
+
}
|
|
59
|
+
if (isPlainObject(value)) {
|
|
60
|
+
return Object.fromEntries(
|
|
61
|
+
Object.entries(value).map(([key, nested]) => [key, deepTrim(nested)])
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
function omitEmpty(value) {
|
|
67
|
+
if (!isPlainObject(value)) {
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
const cleaned = { ...value };
|
|
71
|
+
for (const key of Object.keys(cleaned)) {
|
|
72
|
+
if (cleaned[key] === "" || cleaned[key] === null) {
|
|
73
|
+
delete cleaned[key];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return cleaned;
|
|
77
|
+
}
|
|
78
|
+
function pickAllowed(value, allowed, fallback) {
|
|
79
|
+
return allowed.includes(value) ? value : fallback;
|
|
80
|
+
}
|
|
81
|
+
function sleep(milliseconds) {
|
|
82
|
+
assertFiniteNumber(milliseconds, "milliseconds");
|
|
83
|
+
if (milliseconds < 0) {
|
|
84
|
+
throw new RangeError("milliseconds must be greater than or equal to 0");
|
|
85
|
+
}
|
|
86
|
+
return new Promise((resolve) => {
|
|
87
|
+
setTimeout(resolve, milliseconds);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export { coalesce, deepTrim, isNilOrEmpty, isPlainObject, omitEmpty, pickAllowed, sleep, toBoolean };
|
|
92
|
+
//# sourceMappingURL=index.js.map
|
|
93
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/internal/validation.ts","../../src/common/index.ts"],"names":[],"mappings":";AAAO,SAAS,kBAAA,CACd,OACA,IAAA,EACyB;AACzB,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,EAAG;AACxD,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,EAAG,IAAI,CAAA,wBAAA,CAA0B,CAAA;AAAA,EACvD;AACF;;;ACAO,SAAS,cAAc,KAAA,EAAkD;AAC9E,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,QAAA,EAAU;AAC/C,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,cAAA,CAAe,KAAK,CAAA;AAC7C,EAAA,OAAO,SAAA,KAAc,IAAA,IAAQ,SAAA,KAAc,MAAA,CAAO,SAAA;AACpD;AAMO,SAAS,aAAa,KAAA,EAAyB;AACpD,EAAA,IAAI,SAAS,IAAA,EAAM;AACjB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA,CAAM,IAAA,EAAK,CAAE,MAAA,KAAW,CAAA;AAAA,EACjC;AAEA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,QAAA,CAAY,OAA6B,QAAA,EAAgB;AACvE,EAAA,OAAO,KAAA,IAAS,QAAA;AAClB;AAWO,SAAS,SAAA,CAAU,KAAA,EAAgB,QAAA,GAAW,KAAA,EAAgB;AACnE,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,CAAA,IAAK,UAAU,GAAA,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AA,CAAc,KAAK,CAAA,EAAG;AACzB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,OAAA,GAAU,EAAE,GAAG,KAAA,EAAM;AAC3B,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,EAAG;AACtC,IAAA,IAAI,QAAQ,GAAG,CAAA,KAAM,MAAM,OAAA,CAAQ,GAAG,MAAM,IAAA,EAAM;AAChD,MAAA,OAAO,QAAQ,GAAG,CAAA;AAAA,IACpB;AAAA,EACF;AAEA,EAAA,OAAO,OAAA;AACT;AASO,SAAS,WAAA,CACd,KAAA,EACA,OAAA,EACA,QAAA,EACG;AACH,EAAA,OAAO,OAAA,CAAQ,QAAA,CAAS,KAAU,CAAA,GAAK,KAAA,GAAc,QAAA;AACvD;AAKO,SAAS,MAAM,YAAA,EAAqC;AACzD,EAAA,kBAAA,CAAmB,cAAc,cAAc,CAAA;AAE/C,EAAA,IAAI,eAAe,CAAA,EAAG;AACpB,IAAA,MAAM,IAAI,WAAW,iDAAiD,CAAA;AAAA,EACxE;AAEA,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC9B,IAAA,UAAA,CAAW,SAAS,YAAY,CAAA;AAAA,EAClC,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["export function assertFiniteNumber(\r\n value: unknown,\r\n name: string,\r\n): asserts value is number {\r\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\r\n throw new TypeError(`${name} must be a finite number`);\r\n }\r\n}\r\n\r\nexport function escapeRegExp(value: string): string {\r\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\r\n}\r\n","import { assertFiniteNumber } from \"../internal/validation.js\";\r\n\r\n/**\r\n * Returns `true` when the value is a plain object created by `{}`,\r\n * `Object.create(null)`, or `new Object()`. Arrays, `null`, and class\r\n * instances are rejected.\r\n */\r\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\r\n if (value === null || typeof value !== \"object\") {\r\n return false;\r\n }\r\n\r\n const prototype = Object.getPrototypeOf(value);\r\n return prototype === null || prototype === Object.prototype;\r\n}\r\n\r\n/**\r\n * Returns `true` for `null`, `undefined`, and whitespace-only strings.\r\n * `0` and `false` are not treated as empty.\r\n */\r\nexport function isNilOrEmpty(value: unknown): boolean {\r\n if (value == null) {\r\n return true;\r\n }\r\n\r\n if (typeof value === \"string\") {\r\n return value.trim().length === 0;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n/**\r\n * Returns `value` unless it is `null` or `undefined`, in which case\r\n * `fallback` is returned.\r\n */\r\nexport function coalesce<T>(value: T | null | undefined, fallback: T): T {\r\n return value ?? fallback;\r\n}\r\n\r\n/**\r\n * Coerces common truthy/falsey inputs to a boolean.\r\n * `null`, `undefined`, and empty or whitespace-only strings return `fallback`.\r\n *\r\n * @example\r\n * toBoolean(\"true\") // true\r\n * toBoolean(\"0\") // false\r\n * toBoolean(null, true) // true\r\n */\r\nexport function toBoolean(value: unknown, fallback = false): boolean {\r\n if (value === true || value === 1 || value === \"1\") {\r\n return true;\r\n }\r\n\r\n if (value === false || value === 0 || value === \"0\") {\r\n return false;\r\n }\r\n\r\n if (typeof value === \"string\") {\r\n const normalized = value.trim().toLowerCase();\r\n if (normalized.length === 0) {\r\n return fallback;\r\n }\r\n if (normalized === \"true\") {\r\n return true;\r\n }\r\n if (normalized === \"false\") {\r\n return false;\r\n }\r\n }\r\n\r\n if (value == null) {\r\n return fallback;\r\n }\r\n\r\n return fallback;\r\n}\r\n\r\n/**\r\n * Recursively trims strings in arrays and plain objects.\r\n * Dates, class instances, and other non-plain objects are left unchanged.\r\n *\r\n * @example\r\n * deepTrim({ name: \" Gold \", tags: [\" rsa \"] })\r\n * // { name: \"Gold\", tags: [\"rsa\"] }\r\n */\r\nexport function deepTrim<T>(value: T): T {\r\n if (typeof value === \"string\") {\r\n return value.trim() as T;\r\n }\r\n\r\n if (Array.isArray(value)) {\r\n return value.map((item) => deepTrim(item)) as T;\r\n }\r\n\r\n if (isPlainObject(value)) {\r\n return Object.fromEntries(\r\n Object.entries(value).map(([key, nested]) => [key, deepTrim(nested)]),\r\n ) as T;\r\n }\r\n\r\n return value;\r\n}\r\n\r\n/**\r\n * Returns a shallow copy of a plain object without `null` or empty-string values.\r\n * Non-plain values are returned unchanged.\r\n *\r\n * @example\r\n * omitEmpty({ name: \"Gold\", note: \"\", city: null })\r\n * // { name: \"Gold\" }\r\n */\r\nexport function omitEmpty<T>(value: T): T {\r\n if (!isPlainObject(value)) {\r\n return value;\r\n }\r\n\r\n const cleaned = { ...value };\r\n for (const key of Object.keys(cleaned)) {\r\n if (cleaned[key] === \"\" || cleaned[key] === null) {\r\n delete cleaned[key];\r\n }\r\n }\r\n\r\n return cleaned as T;\r\n}\r\n\r\n/**\r\n * Returns `value` when it is one of the allowed values, otherwise `fallback`.\r\n *\r\n * @example\r\n * pickAllowed(\"hi\", [\"en\", \"hi\"] as const, \"en\") // \"hi\"\r\n * pickAllowed(\"fr\", [\"en\", \"hi\"] as const, \"en\") // \"en\"\r\n */\r\nexport function pickAllowed<T>(\r\n value: unknown,\r\n allowed: readonly T[],\r\n fallback: T,\r\n): T {\r\n return allowed.includes(value as T) ? (value as T) : fallback;\r\n}\r\n\r\n/**\r\n * Resolves after the given number of milliseconds.\r\n */\r\nexport function sleep(milliseconds: number): Promise<void> {\r\n assertFiniteNumber(milliseconds, \"milliseconds\");\r\n\r\n if (milliseconds < 0) {\r\n throw new RangeError(\"milliseconds must be greater than or equal to 0\");\r\n }\r\n\r\n return new Promise((resolve) => {\r\n setTimeout(resolve, milliseconds);\r\n });\r\n}\r\n"]}
|