@talosjs/utils 1.0.0 → 1.1.1

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 (2) hide show
  1. package/README.md +4 -494
  2. package/package.json +3 -3
package/README.md CHANGED
@@ -1,33 +1,6 @@
1
1
  # @talosjs/utils
2
2
 
3
- General-purpose utility functions including unique ID generation with nanoid, type guards, and common helper methods.
4
-
5
- ![Browser](https://img.shields.io/badge/Browser-Compatible-green?style=flat-square&logo=googlechrome)
6
- ![Bun](https://img.shields.io/badge/Bun-Compatible-orange?style=flat-square&logo=bun)
7
- ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)
8
- ![MIT License](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)
9
-
10
- ## Features
11
-
12
- ✅ **ID Generation** - Generate unique IDs using nanoid with configurable length
13
-
14
- ✅ **String Case Conversion** - Convert between camelCase, kebab-case, snake_case, and PascalCase
15
-
16
- ✅ **String Utilities** - `trim`, `splitToWords`, `capitalizeWord` for common string operations
17
-
18
- ✅ **Value Parsing** - `parseString` to convert string values to boolean, number, or string types
19
-
20
- ✅ **Time Formatting** - `secondsToHMS`, `secondsToMS`, and `millisecondsToHMS` for duration display
21
-
22
- ✅ **Number Formatting** - `formatRelativeNumber` for human-readable numbers with K, M, B suffixes
23
-
24
- ✅ **Data Conversion** - `dataURLtoFile` to convert data URLs to File objects
25
-
26
- ✅ **Environment Variables** - `parseEnvVars` to parse .env file content into key-value pairs
27
-
28
- ✅ **Async Utilities** - `sleep` function for async/await workflows
29
-
30
- ✅ **Zero Config** - Simple, pure functions with no configuration needed
3
+ General-purpose utility functions including unique ID generation with nanoid, type guards, and common helper methods
31
4
 
32
5
  ## Installation
33
6
 
@@ -35,473 +8,10 @@ General-purpose utility functions including unique ID generation with nanoid, ty
35
8
  bun add @talosjs/utils
36
9
  ```
37
10
 
38
- ## Usage
39
-
40
- ### Unique ID Generation
41
-
42
- ```typescript
43
- import { random } from '@talosjs/utils';
44
-
45
- // Generate a unique ID (default length: 21)
46
- const id = random();
47
- console.log(id); // "V1StGXR8_Z5jdHi6B-myT"
48
-
49
- // Generate with custom length
50
- const shortId = random(10);
51
- console.log(shortId); // "V1StGXR8_Z"
52
- ```
53
-
54
- ### String Case Conversion
55
-
56
- ```typescript
57
- import {
58
- toCamelCase,
59
- toKebabCase,
60
- toSnakeCase,
61
- toPascalCase,
62
- capitalizeWord
63
- } from '@talosjs/utils';
64
-
65
- // Convert to camelCase
66
- toCamelCase('hello world'); // "helloWorld"
67
- toCamelCase('hello-world'); // "helloWorld"
68
- toCamelCase('hello_world'); // "helloWorld"
69
-
70
- // Convert to kebab-case
71
- toKebabCase('helloWorld'); // "hello-world"
72
- toKebabCase('HelloWorld'); // "hello-world"
73
- toKebabCase('hello_world'); // "hello-world"
74
-
75
- // Convert to snake_case
76
- toSnakeCase('helloWorld'); // "hello_world"
77
- toSnakeCase('HelloWorld'); // "hello_world"
78
- toSnakeCase('hello-world'); // "hello_world"
79
-
80
- // Convert to PascalCase
81
- toPascalCase('hello world'); // "HelloWorld"
82
- toPascalCase('hello-world'); // "HelloWorld"
83
- toPascalCase('hello_world'); // "HelloWorld"
84
-
85
- // Capitalize first letter
86
- capitalizeWord('hello'); // "Hello"
87
- capitalizeWord('hello world'); // "Hello world"
88
- ```
89
-
90
- ### Time Formatting
91
-
92
- ```typescript
93
- import {
94
- secondsToHMS,
95
- secondsToMS,
96
- millisecondsToHMS
97
- } from '@talosjs/utils';
98
-
99
- // Seconds to Hours:Minutes:Seconds
100
- secondsToHMS(3661); // "1:01:01"
101
- secondsToHMS(125); // "0:02:05"
102
-
103
- // Seconds to Minutes:Seconds
104
- secondsToMS(125); // "2:05"
105
- secondsToMS(65); // "1:05"
106
-
107
- // Milliseconds to Hours:Minutes:Seconds
108
- millisecondsToHMS(3661000); // "1:01:01"
109
- millisecondsToHMS(125000); // "0:02:05"
110
- ```
111
-
112
- ### Number Formatting
113
-
114
- ```typescript
115
- import { formatRelativeNumber } from '@talosjs/utils';
116
-
117
- // Format large numbers with suffixes
118
- formatRelativeNumber(1000); // "1K"
119
- formatRelativeNumber(1500); // "1.5K"
120
- formatRelativeNumber(1000000); // "1M"
121
- formatRelativeNumber(1500000); // "1.5M"
122
- formatRelativeNumber(1000000000); // "1B"
123
- formatRelativeNumber(999); // "999"
124
- ```
125
-
126
- ### Async Sleep
127
-
128
- ```typescript
129
- import { sleep } from '@talosjs/utils';
130
-
131
- async function example() {
132
- console.log('Starting...');
133
-
134
- // Wait for 2 seconds
135
- await sleep(2000);
136
-
137
- console.log('2 seconds later...');
138
- }
139
- ```
140
-
141
- ### String Utilities
142
-
143
- ```typescript
144
- import { trim, splitToWords, parseString } from '@talosjs/utils';
145
-
146
- // Trim whitespace and normalize
147
- trim(' hello world '); // "hello world"
148
-
149
- // Split string into words
150
- splitToWords('helloWorld'); // ["hello", "World"]
151
- splitToWords('hello-world'); // ["hello", "world"]
152
- splitToWords('hello_world'); // ["hello", "world"]
153
-
154
- // Parse string values
155
- parseString('true'); // true (boolean)
156
- parseString('false'); // false (boolean)
157
- parseString('123'); // 123 (number)
158
- parseString('hello'); // "hello" (string)
159
- ```
160
-
161
- ### Data URL Conversion
162
-
163
- ```typescript
164
- import { dataURLtoFile } from '@talosjs/utils';
165
-
166
- // Convert a data URL to a File object
167
- const dataUrl = 'data:image/png;base64,iVBORw0KGgo...';
168
- const file = dataURLtoFile(dataUrl, 'image.png');
169
-
170
- console.log(file.name); // "image.png"
171
- console.log(file.type); // "image/png"
172
- ```
173
-
174
- ### Environment Variable Parsing
175
-
176
- ```typescript
177
- import { parseEnvVars } from '@talosjs/utils';
178
-
179
- // Parse environment variable content
180
- const envContent = `
181
- DATABASE_URL=postgresql://localhost:5432/mydb
182
- API_KEY=secret-key-123
183
- DEBUG=true
184
- PORT=3000
185
- `;
186
-
187
- const vars = parseEnvVars(envContent);
188
- // {
189
- // DATABASE_URL: 'postgresql://localhost:5432/mydb',
190
- // API_KEY: 'secret-key-123',
191
- // DEBUG: 'true',
192
- // PORT: '3000'
193
- // }
194
- ```
195
-
196
- ## API Reference
197
-
198
- ### Functions
199
-
200
- #### `random(size?: number): string`
201
-
202
- Generates a unique ID using nanoid.
203
-
204
- **Parameters:**
205
- - `size` - Optional length of the ID (default: 21)
206
-
207
- **Returns:** A unique string ID
208
-
209
- **Example:**
210
- ```typescript
211
- const id = random(); // "V1StGXR8_Z5jdHi6B-myT"
212
- const short = random(8); // "V1StGXR8"
213
- ```
214
-
215
- ---
216
-
217
- #### `toCamelCase(str: string): string`
218
-
219
- Converts a string to camelCase.
220
-
221
- **Parameters:**
222
- - `str` - The input string
223
-
224
- **Returns:** camelCase formatted string
225
-
226
- ---
227
-
228
- #### `toKebabCase(str: string): string`
229
-
230
- Converts a string to kebab-case.
231
-
232
- **Parameters:**
233
- - `str` - The input string
234
-
235
- **Returns:** kebab-case formatted string
236
-
237
- ---
238
-
239
- #### `toSnakeCase(str: string): string`
240
-
241
- Converts a string to snake_case.
242
-
243
- **Parameters:**
244
- - `str` - The input string
245
-
246
- **Returns:** snake_case formatted string
247
-
248
- ---
249
-
250
- #### `toPascalCase(str: string): string`
251
-
252
- Converts a string to PascalCase.
253
-
254
- **Parameters:**
255
- - `str` - The input string
256
-
257
- **Returns:** PascalCase formatted string
258
-
259
- ---
260
-
261
- #### `capitalizeWord(str: string): string`
262
-
263
- Capitalizes the first letter of a string.
11
+ ## Documentation
264
12
 
265
- **Parameters:**
266
- - `str` - The input string
267
-
268
- **Returns:** String with first letter capitalized
269
-
270
- ---
271
-
272
- #### `splitToWords(str: string): string[]`
273
-
274
- Splits a string into an array of words.
275
-
276
- **Parameters:**
277
- - `str` - The input string (camelCase, kebab-case, snake_case, or space-separated)
278
-
279
- **Returns:** Array of words
280
-
281
- ---
282
-
283
- #### `trim(str: string): string`
284
-
285
- Trims whitespace and normalizes internal spacing.
286
-
287
- **Parameters:**
288
- - `str` - The input string
289
-
290
- **Returns:** Trimmed and normalized string
291
-
292
- ---
293
-
294
- #### `secondsToHMS(seconds: number): string`
295
-
296
- Converts seconds to H:MM:SS format.
297
-
298
- **Parameters:**
299
- - `seconds` - Number of seconds
300
-
301
- **Returns:** Formatted time string
302
-
303
- ---
304
-
305
- #### `secondsToMS(seconds: number): string`
306
-
307
- Converts seconds to M:SS format.
308
-
309
- **Parameters:**
310
- - `seconds` - Number of seconds
311
-
312
- **Returns:** Formatted time string
313
-
314
- ---
315
-
316
- #### `millisecondsToHMS(milliseconds: number): string`
317
-
318
- Converts milliseconds to H:MM:SS format.
319
-
320
- **Parameters:**
321
- - `milliseconds` - Number of milliseconds
322
-
323
- **Returns:** Formatted time string
324
-
325
- ---
326
-
327
- #### `formatRelativeNumber(num: number): string`
328
-
329
- Formats a number with K, M, or B suffix.
330
-
331
- **Parameters:**
332
- - `num` - The number to format
333
-
334
- **Returns:** Formatted number string with suffix
335
-
336
- ---
337
-
338
- #### `sleep(ms: number): Promise<void>`
339
-
340
- Pauses execution for the specified duration.
341
-
342
- **Parameters:**
343
- - `ms` - Duration in milliseconds
344
-
345
- **Returns:** Promise that resolves after the duration
346
-
347
- ---
348
-
349
- #### `dataURLtoFile(dataUrl: string, filename: string): File`
350
-
351
- Converts a data URL to a File object.
352
-
353
- **Parameters:**
354
- - `dataUrl` - The data URL string
355
- - `filename` - Name for the resulting file
356
-
357
- **Returns:** File object
358
-
359
- ---
360
-
361
- #### `parseString(value: string): string | number | boolean`
362
-
363
- Parses a string value to its appropriate type.
364
-
365
- **Parameters:**
366
- - `value` - The string to parse
367
-
368
- **Returns:** Parsed value (boolean, number, or string)
369
-
370
- ---
371
-
372
- #### `parseEnvVars(content: string): Record<string, string>`
373
-
374
- Parses environment variable content.
375
-
376
- **Parameters:**
377
- - `content` - Raw environment variable content
378
-
379
- **Returns:** Object with key-value pairs
380
-
381
- ## Advanced Usage
382
-
383
- ### Building File Names
384
-
385
- ```typescript
386
- import { toKebabCase, random } from '@talosjs/utils';
387
-
388
- function generateFileName(title: string, extension: string): string {
389
- const slug = toKebabCase(title);
390
- const uniqueId = random(8);
391
- return `${slug}-${uniqueId}.${extension}`;
392
- }
393
-
394
- const fileName = generateFileName('My Awesome Photo', 'jpg');
395
- // "my-awesome-photo-V1StGXR8.jpg"
396
- ```
397
-
398
- ### Formatting Display Values
399
-
400
- ```typescript
401
- import { formatRelativeNumber, capitalizeWord } from '@talosjs/utils';
402
-
403
- interface SocialStats {
404
- followers: number;
405
- likes: number;
406
- views: number;
407
- }
408
-
409
- function formatStats(stats: SocialStats): Record<string, string> {
410
- return {
411
- followers: formatRelativeNumber(stats.followers),
412
- likes: formatRelativeNumber(stats.likes),
413
- views: formatRelativeNumber(stats.views)
414
- };
415
- }
416
-
417
- const stats = formatStats({
418
- followers: 15600,
419
- likes: 1200000,
420
- views: 45000
421
- });
422
- // { followers: "15.6K", likes: "1.2M", views: "45K" }
423
- ```
424
-
425
- ### Video Duration Display
426
-
427
- ```typescript
428
- import { secondsToHMS, secondsToMS } from '@talosjs/utils';
429
-
430
- function formatDuration(seconds: number): string {
431
- // Use H:MM:SS for videos over an hour, otherwise M:SS
432
- return seconds >= 3600
433
- ? secondsToHMS(seconds)
434
- : secondsToMS(seconds);
435
- }
436
-
437
- console.log(formatDuration(90)); // "1:30"
438
- console.log(formatDuration(3700)); // "1:01:40"
439
- ```
440
-
441
- ### Retry with Delay
442
-
443
- ```typescript
444
- import { sleep } from '@talosjs/utils';
445
-
446
- async function retryWithBackoff<T>(
447
- fn: () => Promise<T>,
448
- maxRetries: number = 3,
449
- baseDelay: number = 1000
450
- ): Promise<T> {
451
- let lastError: Error;
452
-
453
- for (let attempt = 0; attempt < maxRetries; attempt++) {
454
- try {
455
- return await fn();
456
- } catch (error) {
457
- lastError = error as Error;
458
- const delay = baseDelay * Math.pow(2, attempt);
459
- console.log(`Attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
460
- await sleep(delay);
461
- }
462
- }
463
-
464
- throw lastError!;
465
- }
466
- ```
467
-
468
- ### API Route Slug Generation
469
-
470
- ```typescript
471
- import { toKebabCase } from '@talosjs/utils';
472
-
473
- function generateApiSlug(resourceName: string, action: string): string {
474
- const resource = toKebabCase(resourceName);
475
- const actionSlug = toKebabCase(action);
476
- return `/api/${resource}/${actionSlug}`;
477
- }
478
-
479
- generateApiSlug('UserProfile', 'getById'); // "/api/user-profile/get-by-id"
480
- generateApiSlug('BlogPost', 'create'); // "/api/blog-post/create"
481
- ```
13
+ Read the full documentation at [docs.talosjs.com/utilities/utils](https://docs.talosjs.com/utilities/utils).
482
14
 
483
15
  ## License
484
16
 
485
- This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
486
-
487
- ## Contributing
488
-
489
- Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
490
-
491
- ### Development Setup
492
-
493
- 1. Clone the repository
494
- 2. Install dependencies: `bun install`
495
- 3. Run tests: `bun run test`
496
- 4. Build the project: `bun run build`
497
-
498
- ### Guidelines
499
-
500
- - Write tests for new features
501
- - Follow the existing code style
502
- - Update documentation for API changes
503
- - Ensure all tests pass before submitting PR
504
-
505
- ---
506
-
507
- Made with ❤️ by the Talos team
17
+ MIT
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@talosjs/utils",
3
3
  "description": "General-purpose utility functions including unique ID generation with nanoid, type guards, and common helper methods",
4
- "version": "1.0.0",
4
+ "version": "1.1.1",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",
@@ -118,8 +118,8 @@
118
118
  "scripts": {
119
119
  "test": "bun test tests",
120
120
  "build": "bunup",
121
- "lint": "tsgo --noEmit && bunx biome lint",
122
- "npm:publish": "bun publish --tolerate-republish --force --production --access public"
121
+ "fmt": "bunx biome check --write",
122
+ "lint": "tsgo --noEmit && bunx biome lint"
123
123
  },
124
124
  "dependencies": {
125
125
  "nanoid": "^5.1.6"