nu_plugin_nw_ulid 0.2.0

Production-grade ULID (Universally Unique Lexicographically Sortable Identifier) utilities plugin for Nushell with cryptographically secure operations, enterprise-grade security, and streaming support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
# ULID Plugin API Reference

**Version**: 0.1.0  
**Last Updated**: August 17, 2025  
**Compatibility**: Nushell 0.109.1+

Complete reference for all ULID plugin commands and their programmatic usage. This document provides detailed API specifications, parameter descriptions, return types, and advanced usage patterns for developers and script authors.

## Quick Reference

| Command | Purpose | Input Types | Output Types |
|---------|---------|-------------|-------------|
| `ulid generate` | Generate ULIDs | Nothing, Number | String, List<String> |
| `ulid validate` | Validate ULID format | String, List<String> | Bool, List<Record> |
| `ulid parse` | Parse ULID components | String, List<String> | Record, List<Record> |
| `ulid inspect` | Detailed ULID analysis | String | Record |
| `ulid sort` | Sort by ULID timestamp | List<String>, Table | List<String>, Table |
| `ulid security-advice` | Security recommendations | Nothing | Record |
| `ulid time` | Time operations | Various | Record |
| `ulid encode/decode` | Encoding operations | String, Binary | String, Binary |
| `ulid uuid` | UUID compatibility | String | String, Bool, Record |
| `ulid info` | Plugin information | Nothing | Record |

## Core Commands

### `ulid generate`
Generate cryptographically secure ULIDs with optional parameters.

**Full Syntax:**
```nu
ulid generate [--count <int>] [--timestamp <int>]
```

**Parameters:**
- `--count <int>`: Number of ULIDs to generate (1-10,000, default: 1)
- `--timestamp <int>`: Custom timestamp in milliseconds since Unix epoch (optional)

**Input Types:**
- `Nothing`: Generate based on parameters
- `Number`: Use as count parameter

**Output Types:**
- Single ULID: `String` (26 characters)
- Multiple ULIDs: `List<String>`

**Return Value Schema:**
```nu
# Single ULID
"01K2W41TWG3FKYYSK430SR8KW6"

# Multiple ULIDs
[
    "01K2W41TWG3FKYYSK430SR8KW6",
    "01K2W41TWG3FKYYSK430SR8KW7",
    "01K2W41TWG3FKYYSK430SR8KW8"
]

```

**Advanced Examples:**
```nu
# Generate with current timestamp
let current_id = ulid generate

# Generate batch with custom timestamp
let batch_ids = ulid generate --count 100 --timestamp 1692000000000

# Generate and parse for structured output
let detailed_ulid = ulid generate | ulid parse $in

# Generate and convert to binary
let binary_ulid = ulid generate | ulid to-bytes

# Use in pipeline
1..10 | each { ulid generate } | str join ","

# Generate time-ordered sequence
let ordered_ids = (0..5 | each { |i| 
    ulid generate --timestamp (date now | into int | $in + ($i * 1000))
})
```

**Error Conditions:**
- `InvalidParameter`: Count exceeds maximum (100,000)
- `InvalidTimestamp`: Timestamp is negative or too large
### `ulid validate`
Validate ULID format, structure, and integrity.

**Full Syntax:**
```nu
ulid validate <ulid> [--strict] [--details]
```

**Parameters:**
- `<ulid>`: ULID string to validate (required)
- `--strict`: Enable strict validation (checks timestamp bounds)
- `--details`: Return detailed validation results instead of boolean

**Input Types:**
- `String`: Single ULID to validate
- `List<String>`: Multiple ULIDs to validate

**Output Types:**
- Single validation: `Bool` (default) or `Record` (with --details)
- Multiple validations: `List<Record>`

**Return Value Schema:**
```nu
# Simple validation
true  # or false

# Detailed validation
{
    ulid: "01K2W41TWG3FKYYSK430SR8KW6",
    valid: true,
    format_valid: true,
    timestamp_valid: true,
    randomness_valid: true,
    length_valid: true,
    encoding_valid: true,
    warnings: []
}

# Multiple ULIDs
[
    { ulid: "01K2W41TWG3FKYYSK430SR8KW6", valid: true },
    { ulid: "invalid-ulid", valid: false, error: "Invalid length" }
]
```

**Advanced Examples:**
```nu
# Simple validation
if (ulid validate "01K2W41TWG3FKYYSK430SR8KW6") {
    print "Valid ULID"
}

# Detailed validation with error information
let validation = ulid validate "01K2W41TWG3FKYYSK430SR8KW6" --details
if not $validation.valid {
    print $"Validation failed: ($validation.error)"
}

# Validate with strict timestamp checking
let strict_result = ulid validate $ulid --strict

# Batch validation with error handling
let results = $ulid_list | each { |id|
    try {
        { ulid: $id, valid: (ulid validate $id), error: null }
    } catch { |e|
        { ulid: $id, valid: false, error: $e.msg }
    }
}

# Filter valid ULIDs from mixed data
let valid_ulids = $mixed_data 
    | where { ulid validate $in.id }
    | get id

```

**Error Conditions:**
- `InvalidInput`: Input is not a string
- `EmptyInput`: Input string is empty
- `InvalidFormat`: ULID format is incorrect

### `ulid parse`
Parse ULID into timestamp, randomness, and metadata components.

**Full Syntax:**
```nu
ulid parse <ulid>
```

**Parameters:**
- `<ulid>`: ULID string to parse (required)

**Input Types:**
- `String`: Single ULID to parse
- `List<String>`: Multiple ULIDs to parse

**Output Types:**
- Single parse: `Record`
- Multiple parses: `List<Record>`

**Return Value Schema:**
```nu
# Standard format
{
    ulid: "01K2W41TWG3FKYYSK430SR8KW6",
    timestamp: {
        milliseconds: 1692817394611,
        iso8601: "2023-08-23T18:49:54.611Z",
        human: "2023-08-23 18:49:54 UTC",
        unix: 1692817394
    },
    randomness: {
        hex: "F2Y5SK430SR8KW6",
        bytes: [242, 89, 83, 75, 52, 48, 83, 82, 56, 75, 87, 54]
    },
    valid: true
}

```

**Advanced Examples:**
```nu
# Parse and check validity
let parsed = ulid parse "01K2W41TWG3FKYYSK430SR8KW6"
if not $parsed.valid {
    error make { msg: "Invalid ULID" }
}

# Batch parsing with error handling
let parsed_ulids = $ulid_list | each { |id|
    try {
        ulid parse $id
    } catch {
        { ulid: $id, valid: false, error: "Parse failed" }
    }
}

# Extract randomness for uniqueness analysis
let randomness_values = $ulids | each { |id|
    ulid parse $id | get randomness.hex
} | uniq | length
```

**Error Conditions:**
- `InvalidFormat`: ULID format is incorrect
- `ParseError`: Unable to parse timestamp or randomness
- `InvalidTimezone`: Specified timezone is not recognized

### `ulid inspect`
Comprehensive ULID analysis with detailed metadata and statistics.

**Full Syntax:**
```nu
ulid inspect <ulid> [--compact] [--timestamp-only] [--stats]
```

**Parameters:**
- `<ulid>`: ULID string to inspect (required)
- `--compact`: Return condensed output format
- `--timestamp-only`: Return only timestamp-related information
- `--stats`: Include statistical analysis (entropy, patterns)

**Input Types:**
- `String`: Single ULID to inspect

**Output Types:**
- `Record`: Detailed inspection results

**Return Value Schema:**
```nu
# Standard inspection
{
    ulid: "01K2W41TWG3FKYYSK430SR8KW6",
    valid: true,
    timestamp: {
        milliseconds: 1692817394611,
        iso8601: "2023-08-23T18:49:54.611Z",
        human: "2023-08-23 18:49:54 UTC",
        unix: 1692817394,
        age_seconds: 86400,
        age_human: "1 day ago"
    },
    randomness: {
        hex: "F2Y5SK430SR8KW6",
        bytes: [242, 89, 83, 75, 52, 48, 83, 82, 56, 75, 87, 54],
        entropy_bits: 80
    },
    metadata: {
        length: 26,
        encoding: "crockford_base32",
        version: "ulid",
        monotonic: true
    }
}

# With statistics
{
    # ... standard fields ...
    statistics: {
        character_distribution: {...},
        entropy_analysis: {...},
        pattern_detection: {...}
    }
}

# Security check
{
    # ... standard fields ...
    security: {
        context_warnings: [],
        predictability_risk: "low",
        collision_probability: 2.3e-24
    }
}
```

**Advanced Examples:**
```nu
# Full inspection with all options
let full_analysis = ulid inspect $ulid --stats --security-check

# Quick timestamp check
let age = ulid inspect $ulid --timestamp-only | get age_human

# Compact inspection for logging
let log_entry = ulid inspect $request_id --compact

# Security analysis for API keys
let security_info = ulid inspect $api_key --security-check
if ($security_info.security.predictability_risk == "high") {
    print "WARNING: Predictable ULID detected"
}

# Batch inspection for analysis
let inspections = $ulid_list | each { |id|
    ulid inspect $id --compact
}

# Extract creation times for timeline analysis
let timeline = $ulids | each { |id|
    let inspection = ulid inspect $id --timestamp-only
    {
        ulid: $id,
        created: $inspection.timestamp.iso8601,
        age: $inspection.age_human
    }
} | sort-by created
```

### `ulid sort`
Sort data by ULID timestamp order.

**Syntax:**
```nu
ulid sort [--column <string>] [--reverse] [--natural]
```

**Scripting Examples:**
```nu
# Sort ULID list
$ulids | ulid sort

# Sort records by ULID column
$records | ulid sort --column id

# Reverse chronological order
$ulids | ulid sort --reverse
```

## Utility Commands

### `ulid security-advice`
Get security recommendations for ULID usage.

**Syntax:**
```nu
ulid security-advice
```

**Scripting Examples:**
```nu
# Get security advice
let advice = ulid security-advice
```

## Error Handling Patterns

### Try-Catch Pattern
```nu
def safe_ulid_operation [ulid: string] {
    try {
        ulid parse $ulid
    } catch {
        { error: $"Invalid ULID: ($ulid)", success: false }
    }
}
```

### Validation Pattern
```nu
def process_if_valid [ulid: string] {
    if (ulid validate $ulid) {
        # Process valid ULID
        ulid parse $ulid
    } else {
        # Handle invalid ULID
        { error: "Invalid ULID", ulid: $ulid }
    }
}
```

### Bulk Processing Pattern
```nu
def process_ulid_list [ulids: list] {
    $ulids | each { |ulid|
        if (ulid validate $ulid) {
            { ulid: $ulid, parsed: (ulid parse $ulid), valid: true }
        } else {
            { ulid: $ulid, error: "Invalid", valid: false }
        }
    }
}
```

## Performance Guidelines

### Memory Efficiency
- Process data in chunks rather than loading everything at once
- Cache parsed results when processing the same ULIDs multiple times

### CPU Optimization
- Enable parallel processing for CPU-intensive operations
- Use bulk generation instead of individual ULID generation
- Cache parsed results when processing the same ULIDs multiple times

### Pipeline Integration
```nu
# Efficient pipeline pattern
$data 
| where valid_record 
| ulid sort --column id 
| select id timestamp data
| save processed_data.json
```

## Common Integration Patterns

### Database ID Generation
```nu
def add_ids_to_records [records: list] {
    let count = ($records | length)
    let ids = (1..$count | each { ulid generate })
    $records | enumerate | each { |row|
        $row.item | upsert id ($ids | get $row.index)
    }
}
```

### Log Processing
```nu
def process_logs_by_time [logs: list] {
    $logs 
    | ulid sort --column request_id 
    | group-by { |log| 
        ulid parse $log.request_id | get timestamp.iso8601 | str substring 0..13
    }
}
```

### Data Validation
```nu
def validate_data_integrity [data: list] {
    let total = ($data | length)
    let valid = ($data | where { ulid validate $in.id } | length)
    { total: $total, valid: $valid, invalid: ($total - $valid) }
}
```

## Advanced Usage Patterns

### Batch Processing Strategies

#### Memory-Efficient Processing
```nu
# Process large datasets without loading everything into memory
def process_ulid_file [file_path: string] {
    open $file_path
    | get ulids
    | chunks 1000  # Process in 1000-item chunks
    | each { |chunk|
        $chunk | each { |ulid|
            try {
                { ulid: $ulid, valid: (ulid validate $ulid) }
            } catch {
                { ulid: $ulid, valid: false }
            }
        }
    }
    | flatten
}
```

#### Batch Processing
```nu
# Process a list of ULIDs with error handling
def batch_ulid_processing [ulids: list] {
    $ulids | each { |ulid|
        try {
            { ulid: $ulid, parsed: (ulid parse $ulid), valid: true }
        } catch {
            { ulid: $ulid, error: "Invalid", valid: false }
        }
    }
}
```

### Error Handling Patterns

#### Graceful Error Recovery
```nu
def robust_ulid_processor [ulids: list] {
    $ulids | each { |ulid|
        try {
            let parsed = ulid parse $ulid --validate
            { 
                ulid: $ulid, 
                success: true, 
                timestamp: $parsed.timestamp.milliseconds,
                error: null 
            }
        } catch { |e|
            { 
                ulid: $ulid, 
                success: false, 
                timestamp: null,
                error: $e.msg 
            }
        }
    }
}
```

#### Error Aggregation and Reporting
```nu
def process_with_error_report [ulids: list] {
    let results = $ulids | robust_ulid_processor
    let errors = $results | where success == false
    let successes = $results | where success == true
    
    {
        total_processed: ($results | length),
        successful: ($successes | length),
        failed: ($errors | length),
        success_rate: (($successes | length) / ($results | length) * 100),
        error_summary: ($errors | group-by error | transpose error count),
        results: $results
    }
}
```

### Performance Optimization

#### Parallel Processing with Work Distribution
```nu
# Distribute work across multiple parallel streams
def parallel_ulid_analysis [ulids: list, num_workers: int = 4] {
    let chunk_size = (($ulids | length) / $num_workers | math ceil)
    
    $ulids 
    | chunks $chunk_size
    | par-each { |chunk|
        $chunk | each { |ulid| ulid parse $ulid }
    }
    | flatten
}
```

#### Caching and Memoization
```nu
# Cache parsed ULID results for repeated access
mut $ulid_cache = {}

def cached_ulid_parse [ulid: string] {
    if $ulid in $ulid_cache {
        $ulid_cache | get $ulid
    } else {
        let parsed = ulid parse $ulid
        $ulid_cache = ($ulid_cache | upsert $ulid $parsed)
        $parsed
    }
}
```

### Security-Aware Processing

#### Context-Sensitive Validation
```nu
def secure_ulid_validator [ulids: list] {
    $ulids | each { |ulid|
        # Basic validation
        let basic_valid = ulid validate $ulid
        
        # Enhanced validation
        let enhanced_valid = if $basic_valid {
            let inspection = ulid inspect $ulid --security-check
            $basic_valid and ($inspection.security.predictability_risk != "high")
        } else {
            $basic_valid
        }
        
        {
            ulid: $ulid,
            basic_valid: $basic_valid,
            security_valid: $enhanced_valid,
        }
    }
}
```

#### Audit Trail Generation
```nu
def create_ulid_audit_trail [operations: list] {
    $operations | each { |op|
        let timestamp = date now
        let audit_id = ulid generate
        
        {
            audit_id: $audit_id,
            timestamp: $timestamp,
            operation: $op.type,
            ulid_processed: $op.ulid,
            result: $op.result,
            security_context: $op.context,
            user: (whoami),
            checksum: ([$op.ulid, $op.result, $timestamp] | str join "|")
        }
    }
}
```

### Integration Patterns

#### Database Integration
```nu
# Prepare ULIDs for database insertion
def prepare_db_records [records: list] {
    let timestamp = date now | into int
    
    $records | each { |record|
        let id = ulid generate --timestamp $timestamp
        $record 
        | upsert id $id
        | upsert created_at (ulid parse $id | get timestamp.iso8601)
        | upsert created_timestamp $timestamp
    }
}
```

#### API Response Processing
```nu
# Process API responses containing ULIDs
def process_api_response [response: record] {
    let processed_items = $response.items | each { |item|
        if (ulid validate $item.id) {
            let parsed = ulid parse $item.id
            $item 
            | upsert created_time $parsed.timestamp.human
            | upsert age_seconds (date now | into int | $in - $parsed.timestamp.unix)
        } else {
            $item | upsert error "Invalid ULID"
        }
    }
    
    $response | upsert items $processed_items
}
```

### Monitoring and Analytics

#### Performance Metrics Collection
```nu
def collect_ulid_metrics [operations: list] {
    let start_time = date now | into int
    
    let results = $operations | each { |op|
        let op_start = date now | into int
        let result = (do $op.command)
        let op_end = date now | into int
        
        {
            operation: $op.name,
            duration_ms: ($op_end - $op_start),
            success: ($result != null),
            items_processed: ($result | length),
            throughput: (($result | length) / (($op_end - $op_start) / 1000))
        }
    }
    
    let end_time = date now | into int
    
    {
        total_duration_ms: ($end_time - $start_time),
        operations: $results,
        total_throughput: ($results | get items_processed | math sum) / (($end_time - $start_time) / 1000),
        success_rate: (($results | where success | length) / ($results | length) * 100)
    }
}
```

#### ULID Pattern Analysis
```nu
def analyze_ulid_patterns [ulids: list] {
    let parsed_ulids = $ulids | each { ulid parse $in }
    
    {
        total_ulids: ($ulids | length),
        time_span: {
            earliest: ($parsed_ulids | get timestamp.milliseconds | math min),
            latest: ($parsed_ulids | get timestamp.milliseconds | math max),
            duration_hours: (($parsed_ulids | get timestamp.milliseconds | math max) - ($parsed_ulids | get timestamp.milliseconds | math min)) / 3600000
        },
        distribution: {
            hourly: ($parsed_ulids | group-by { |p| $p.timestamp.iso8601 | str substring 0..13 } | transpose hour count),
            daily: ($parsed_ulids | group-by { |p| $p.timestamp.iso8601 | str substring 0..10 } | transpose day count)
        },
        randomness_analysis: {
            unique_randomness: ($parsed_ulids | get randomness.hex | uniq | length),
            entropy_estimate: ($parsed_ulids | get randomness.hex | uniq | length) / ($parsed_ulids | length)
        }
    }
}
```

## API Reference Summary

This comprehensive API reference provides detailed specifications for all nu_plugin_nw_ulid commands. Key features:

- **Type-safe operations** with comprehensive input/output type specifications
- **Performance optimization** through streaming and parallel processing
- **Security-first design** with context-aware validation and warnings
- **Error resilience** with graceful error handling and recovery patterns
- **Enterprise-grade quality** with comprehensive validation and audit capabilities

For additional examples and use cases, see:
- [User Guide]../USER_GUIDE.md - Complete user documentation
- [Scripting Guide]README.md - Automation patterns and workflows
- [Developer Guide]../DEVELOPER_GUIDE.md - Internal architecture and contribution guidelines