indusagi-coding-agent 0.1.28 → 0.1.30

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 (147) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE.md +22 -0
  3. package/README.md +2 -0
  4. package/dist/core/messages.d.ts +1 -76
  5. package/dist/core/messages.d.ts.map +1 -1
  6. package/dist/core/messages.js +1 -122
  7. package/dist/core/messages.js.map +1 -1
  8. package/dist/core/session-manager.d.ts +1 -447
  9. package/dist/core/session-manager.d.ts.map +1 -1
  10. package/dist/core/session-manager.js +1 -1203
  11. package/dist/core/session-manager.js.map +1 -1
  12. package/package.json +2 -2
  13. package/docs/COMPLETE-GUIDE.md +0 -300
  14. package/docs/COMPREHENSIVE-CLI-SUMMARY.md +0 -900
  15. package/docs/MODES-ARCHITECTURE.md +0 -565
  16. package/docs/PRINT-MODE-GUIDE.md +0 -456
  17. package/docs/README.md +0 -78
  18. package/docs/RPC-GUIDE.md +0 -705
  19. package/docs/UTILS-IMPLEMENTATION-SUMMARY.md +0 -647
  20. package/docs/UTILS-MODULE-OVERVIEW.md +0 -1480
  21. package/docs/UTILS-QA-CHECKLIST.md +0 -1061
  22. package/docs/UTILS-USAGE-GUIDE.md +0 -1419
  23. package/docs/compaction.md +0 -390
  24. package/docs/custom-provider.md +0 -538
  25. package/docs/development.md +0 -69
  26. package/docs/extensions.md +0 -1733
  27. package/docs/hooks.md +0 -378
  28. package/docs/images/doom-extension.png +0 -0
  29. package/docs/images/interactive-mode.png +0 -0
  30. package/docs/images/tree-view.png +0 -0
  31. package/docs/json.md +0 -79
  32. package/docs/keybindings.md +0 -162
  33. package/docs/models.md +0 -193
  34. package/docs/packages.md +0 -163
  35. package/docs/prompt-templates.md +0 -67
  36. package/docs/providers.md +0 -147
  37. package/docs/rpc.md +0 -1048
  38. package/docs/sdk.md +0 -969
  39. package/docs/session.md +0 -412
  40. package/docs/settings.md +0 -219
  41. package/docs/shell-aliases.md +0 -13
  42. package/docs/skills.md +0 -226
  43. package/docs/subagents.md +0 -225
  44. package/docs/terminal-setup.md +0 -65
  45. package/docs/themes.md +0 -295
  46. package/docs/tree.md +0 -219
  47. package/docs/tui.md +0 -887
  48. package/docs/web-tools.md +0 -304
  49. package/docs/windows.md +0 -17
  50. package/examples/README.md +0 -25
  51. package/examples/extensions/README.md +0 -192
  52. package/examples/extensions/antigravity-image-gen.ts +0 -414
  53. package/examples/extensions/auto-commit-on-exit.ts +0 -49
  54. package/examples/extensions/bookmark.ts +0 -50
  55. package/examples/extensions/claude-rules.ts +0 -86
  56. package/examples/extensions/confirm-destructive.ts +0 -59
  57. package/examples/extensions/custom-compaction.ts +0 -115
  58. package/examples/extensions/custom-footer.ts +0 -65
  59. package/examples/extensions/custom-header.ts +0 -73
  60. package/examples/extensions/custom-provider-anthropic/index.ts +0 -605
  61. package/examples/extensions/custom-provider-anthropic/package-lock.json +0 -24
  62. package/examples/extensions/custom-provider-anthropic/package.json +0 -19
  63. package/examples/extensions/custom-provider-gitlab-duo/index.ts +0 -350
  64. package/examples/extensions/custom-provider-gitlab-duo/package.json +0 -16
  65. package/examples/extensions/custom-provider-gitlab-duo/test.ts +0 -83
  66. package/examples/extensions/dirty-repo-guard.ts +0 -56
  67. package/examples/extensions/doom-overlay/README.md +0 -46
  68. package/examples/extensions/doom-overlay/doom/build/doom.js +0 -21
  69. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  70. package/examples/extensions/doom-overlay/doom/build.sh +0 -152
  71. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +0 -72
  72. package/examples/extensions/doom-overlay/doom-component.ts +0 -133
  73. package/examples/extensions/doom-overlay/doom-engine.ts +0 -173
  74. package/examples/extensions/doom-overlay/doom-keys.ts +0 -105
  75. package/examples/extensions/doom-overlay/index.ts +0 -74
  76. package/examples/extensions/doom-overlay/wad-finder.ts +0 -51
  77. package/examples/extensions/event-bus.ts +0 -43
  78. package/examples/extensions/file-trigger.ts +0 -41
  79. package/examples/extensions/git-checkpoint.ts +0 -53
  80. package/examples/extensions/handoff.ts +0 -151
  81. package/examples/extensions/hello.ts +0 -25
  82. package/examples/extensions/inline-bash.ts +0 -94
  83. package/examples/extensions/input-transform.ts +0 -43
  84. package/examples/extensions/interactive-shell.ts +0 -196
  85. package/examples/extensions/mac-system-theme.ts +0 -47
  86. package/examples/extensions/message-renderer.ts +0 -60
  87. package/examples/extensions/modal-editor.ts +0 -86
  88. package/examples/extensions/model-status.ts +0 -31
  89. package/examples/extensions/notify.ts +0 -25
  90. package/examples/extensions/overlay-qa-tests.ts +0 -882
  91. package/examples/extensions/overlay-test.ts +0 -151
  92. package/examples/extensions/permission-gate.ts +0 -34
  93. package/examples/extensions/pirate.ts +0 -47
  94. package/examples/extensions/plan-mode/README.md +0 -65
  95. package/examples/extensions/plan-mode/index.ts +0 -341
  96. package/examples/extensions/plan-mode/utils.ts +0 -168
  97. package/examples/extensions/preset.ts +0 -399
  98. package/examples/extensions/protected-paths.ts +0 -30
  99. package/examples/extensions/qna.ts +0 -120
  100. package/examples/extensions/question.ts +0 -265
  101. package/examples/extensions/questionnaire.ts +0 -428
  102. package/examples/extensions/rainbow-editor.ts +0 -88
  103. package/examples/extensions/sandbox/index.ts +0 -318
  104. package/examples/extensions/sandbox/package-lock.json +0 -92
  105. package/examples/extensions/sandbox/package.json +0 -19
  106. package/examples/extensions/send-user-message.ts +0 -97
  107. package/examples/extensions/session-name.ts +0 -27
  108. package/examples/extensions/shutdown-command.ts +0 -63
  109. package/examples/extensions/snake.ts +0 -344
  110. package/examples/extensions/space-invaders.ts +0 -561
  111. package/examples/extensions/ssh.ts +0 -220
  112. package/examples/extensions/status-line.ts +0 -40
  113. package/examples/extensions/subagent/README.md +0 -172
  114. package/examples/extensions/subagent/agents/planner.md +0 -37
  115. package/examples/extensions/subagent/agents/reviewer.md +0 -35
  116. package/examples/extensions/subagent/agents/scout.md +0 -50
  117. package/examples/extensions/subagent/agents/worker.md +0 -24
  118. package/examples/extensions/subagent/agents.ts +0 -127
  119. package/examples/extensions/subagent/index.ts +0 -964
  120. package/examples/extensions/subagent/prompts/implement-and-review.md +0 -10
  121. package/examples/extensions/subagent/prompts/implement.md +0 -10
  122. package/examples/extensions/subagent/prompts/scout-and-plan.md +0 -9
  123. package/examples/extensions/summarize.ts +0 -196
  124. package/examples/extensions/timed-confirm.ts +0 -70
  125. package/examples/extensions/todo.ts +0 -300
  126. package/examples/extensions/tool-override.ts +0 -144
  127. package/examples/extensions/tools.ts +0 -147
  128. package/examples/extensions/trigger-compact.ts +0 -40
  129. package/examples/extensions/truncated-tool.ts +0 -193
  130. package/examples/extensions/widget-placement.ts +0 -17
  131. package/examples/extensions/with-deps/index.ts +0 -36
  132. package/examples/extensions/with-deps/package-lock.json +0 -31
  133. package/examples/extensions/with-deps/package.json +0 -22
  134. package/examples/sdk/01-minimal.ts +0 -22
  135. package/examples/sdk/02-custom-model.ts +0 -50
  136. package/examples/sdk/03-custom-prompt.ts +0 -55
  137. package/examples/sdk/04-skills.ts +0 -46
  138. package/examples/sdk/05-tools.ts +0 -56
  139. package/examples/sdk/06-extensions.ts +0 -88
  140. package/examples/sdk/07-context-files.ts +0 -40
  141. package/examples/sdk/08-prompt-templates.ts +0 -47
  142. package/examples/sdk/09-api-keys-and-oauth.ts +0 -48
  143. package/examples/sdk/10-settings.ts +0 -38
  144. package/examples/sdk/11-sessions.ts +0 -48
  145. package/examples/sdk/12-full-control.ts +0 -82
  146. package/examples/sdk/13-codex-oauth.ts +0 -37
  147. package/examples/sdk/README.md +0 -144
@@ -1,1480 +0,0 @@
1
- # Utils Module Overview
2
-
3
- **Version**: 1.0.0
4
- **Last Updated**: February 2024
5
- **Status**: Production Ready
6
-
7
- ---
8
-
9
- ## Table of Contents
10
-
11
- 1. [Introduction](#introduction)
12
- 2. [Module Architecture](#module-architecture)
13
- 3. [Complete Utilities Reference](#complete-utilities-reference)
14
- 4. [Utility Categories](#utility-categories)
15
- 5. [Quick Reference Table](#quick-reference-table)
16
- 6. [Common Patterns](#common-patterns)
17
- 7. [Error Handling Best Practices](#error-handling-best-practices)
18
- 8. [Performance Guidelines](#performance-guidelines)
19
- 9. [Security Considerations](#security-considerations)
20
- 10. [Quick Start Examples](#quick-start-examples)
21
- 11. [Troubleshooting Guide](#troubleshooting-guide)
22
-
23
- ---
24
-
25
- ## Introduction
26
-
27
- The **Utils Module** (`src/utils/`) provides a comprehensive collection of 24 specialized utilities designed to handle common operations in the indusagi coding agent. These utilities are organized into logical categories and follow consistent patterns for error handling, type safety, and performance optimization.
28
-
29
- ### Key Features
30
-
31
- - **Modular Design**: Each utility is self-contained and independently importable
32
- - **Type Safety**: Full TypeScript support with proper type definitions
33
- - **Error Handling**: Comprehensive error handling with recovery suggestions
34
- - **Performance**: Optimized algorithms with documented complexity
35
- - **Security**: Built-in protection against common vulnerabilities
36
- - **Testing**: Extensive test coverage with edge cases
37
-
38
- ### Module Statistics
39
-
40
- ```
41
- Total Utilities: 24
42
- Categories: 6
43
- Lines of Code: ~15,000+
44
- Test Cases: 200+
45
- Test Coverage: 85%+
46
- ```
47
-
48
- ---
49
-
50
- ## Module Architecture
51
-
52
- ### File Structure
53
-
54
- ```
55
- src/utils/
56
- ├── __tests__/ # Comprehensive test suite
57
- │ ├── array.test.ts
58
- │ ├── changelog.test.ts
59
- │ ├── clipboard.test.ts
60
- │ ├── error-handler.test.ts
61
- │ └── ... (more test files)
62
-
63
- ├── array.ts # Array manipulation (25+ functions)
64
- ├── changelog.ts # Changelog generation & parsing
65
- ├── clipboard.ts # Clipboard operations
66
- ├── clipboard-image.ts # Image clipboard handling
67
- ├── color-formatter.ts # Color utilities
68
- ├── data-transformer.ts # Data transformation pipeline
69
- ├── date-formatter.ts # Date/time formatting
70
- ├── error-handler.ts # Error handling & recovery
71
- ├── file-operations.ts # File I/O with safety
72
- ├── frontmatter.ts # YAML frontmatter parsing
73
- ├── git.ts # Git operations wrapper
74
- ├── image-convert.ts # Image format conversion
75
- ├── image-resize.ts # Image resizing & optimization
76
- ├── json-formatter.ts # JSON processing utilities
77
- ├── logger.ts # Structured logging
78
- ├── markdown-formatter.ts # Markdown processing
79
- ├── mime.ts # MIME type detection
80
- ├── path-validator.ts # Path validation & resolution
81
- ├── photon.ts # Image processing via Photon
82
- ├── shell.ts # Safe shell command execution
83
- ├── sleep.ts # Async delays & timing
84
- ├── string-formatter.ts # String manipulation
85
- ├── tools-manager.ts # Tool registry management
86
- └── type-guards.ts # Runtime type checking
87
- ```
88
-
89
- ---
90
-
91
- ## Complete Utilities Reference
92
-
93
- ### 1. Array Utilities (`array.ts`)
94
-
95
- **Purpose**: Advanced array manipulation with functional programming patterns
96
-
97
- **Key Functions** (25+):
98
- - `groupBy()` - Group items by key function
99
- - `unique()` - Remove duplicates while preserving order
100
- - `flatten()` - Flatten nested arrays to depth
101
- - `chunk()` - Split array into chunks
102
- - `sortBy()` - Custom sorting
103
- - `partition()` - Split into two arrays by predicate
104
- - `zip()` / `unzip()` - Array zipping operations
105
- - `take()` / `takeLast()` - Get first/last n items
106
- - `drop()` / `dropLast()` - Remove first/last n items
107
- - `union()` / `intersection()` / `difference()` - Set operations
108
- - `minBy()` / `maxBy()` - Find extremes
109
- - `sum()` / `average()` - Numeric aggregations
110
- - `shuffle()` / `sample()` / `sampleSize()` - Randomization
111
-
112
- **Performance**: O(n) to O(n log n) depending on operation
113
-
114
- **Example Usage**:
115
- ```typescript
116
- const users = [{ role: 'admin' }, { role: 'user' }, { role: 'admin' }];
117
- const grouped = groupBy(users, u => u.role);
118
- const unique = unique([1, 2, 2, 3, 3, 3]);
119
- const chunked = chunk([1,2,3,4,5], 2); // [[1,2], [3,4], [5]]
120
- ```
121
-
122
- ---
123
-
124
- ### 2. Error Handler (`error-handler.ts`)
125
-
126
- **Purpose**: Robust error handling with user-friendly messages and recovery suggestions
127
-
128
- **Key Functions** (8):
129
- - `categorizeError()` - Classify error by type
130
- - `extractStackTrace()` - Get formatted stack trace
131
- - `sanitizeErrorMessage()` - Remove sensitive information
132
- - `extractErrorMessage()` - Unified message extraction
133
- - `getRecoverySuggestions()` - Get user-facing recovery steps
134
- - `formatErrorForUser()` - Main error formatting function
135
- - `handlePromise()` - Promise error wrapping (Go-style)
136
- - `retryWithBackoff()` - Exponential backoff retry logic
137
-
138
- **Error Codes**:
139
- ```
140
- E001 - Unknown error
141
- E002 - Validation error
142
- E003 - Configuration error
143
- E004 - Permission denied
144
- E005 - Resource not found
145
- E006 - Timeout error
146
- E007 - Network error
147
- E008 - Parse error
148
- EACCES - Permission denied (POSIX)
149
- ENOENT - File not found (POSIX)
150
- ETIMEDOUT - Connection timeout (POSIX)
151
- ECONNREFUSED - Connection refused (POSIX)
152
- ```
153
-
154
- **Example Usage**:
155
- ```typescript
156
- try {
157
- await riskyOperation();
158
- } catch (error) {
159
- const formatted = formatErrorForUser(error, { code: 'ENOENT' });
160
- console.log(formatted.message);
161
- console.log(formatted.suggestions);
162
- }
163
- ```
164
-
165
- ---
166
-
167
- ### 3. Logger (`logger.ts`)
168
-
169
- **Purpose**: Structured logging with levels, context, and performance tracking
170
-
171
- **Key Functions** (8):
172
- - `createLogger()` - Create named logger instance
173
- - `setLogLevel()` / `getLogLevel()` - Control logging verbosity
174
- - `createScopedLogger()` - Logger with automatic context
175
- - `logGroup()` - Grouped log output
176
- - `logBatch()` - Batch log entries
177
- - `createPerformanceMonitor()` - Track function performance
178
- - `clearLoggers()` - Reset all loggers
179
- - `getActiveLoggers()` - List active loggers
180
-
181
- **Log Levels** (in order):
182
- - DEBUG (0) - Detailed diagnostic info
183
- - INFO (1) - General information
184
- - WARN (2) - Warning messages
185
- - ERROR (3) - Error messages
186
- - FATAL (4) - Critical errors
187
-
188
- **Example Usage**:
189
- ```typescript
190
- const log = createLogger('Database');
191
- setLogLevel('debug');
192
- log.info('Connected', { connection: 'postgres' });
193
-
194
- const timer = log.time('query');
195
- await db.query('SELECT *');
196
- timer(); // Logs duration
197
-
198
- const scoped = createScopedLogger(log, 'request-123', { userId: 42 });
199
- scoped.info('Processing'); // Includes userId
200
- ```
201
-
202
- ---
203
-
204
- ### 4. File Operations (`file-operations.ts`)
205
-
206
- **Purpose**: Safe file and directory operations with error recovery
207
-
208
- **Key Functions** (15+):
209
- - `readFile()` / `readFileBuffer()` - Safe file reading
210
- - `writeFile()` / `appendFile()` - Safe file writing
211
- - `exists()` - Check existence
212
- - `deleteFile()` - Delete with optional backup
213
- - `getSize()` / `getModTime()` - File metadata
214
- - `isDirectory()` / `isFile()` - Type checking
215
- - `listFiles()` - Directory listing with filtering
216
- - `getMetadata()` - Comprehensive metadata
217
- - `readLinesSync()` - Line-by-line reading
218
- - `copyFile()` - Copy with verification
219
- - `batchProcessFiles()` - Process multiple files
220
- - `ensureDir()` - Ensure directory exists
221
- - `glob()` - Pattern matching
222
-
223
- **Example Usage**:
224
- ```typescript
225
- const content = await readFile('./data.json');
226
- await writeFile('./backup.json', content, { createDirs: true });
227
- const files = await listFiles('./src', { extension: '.ts', recursive: true });
228
- const meta = await getMetadata('./config.json', true); // Include hash
229
- ```
230
-
231
- ---
232
-
233
- ### 5. String Formatter (`string-formatter.ts`)
234
-
235
- **Purpose**: String manipulation and formatting utilities
236
-
237
- **Key Functions**:
238
- - `capitalize()` - Capitalize first letter
239
- - `toCamelCase()` / `toSnakeCase()` / `toKebabCase()` - Case conversion
240
- - `truncate()` - Truncate with ellipsis
241
- - `padStart()` / `padEnd()` - Padding utilities
242
- - `repeat()` - Repeat string
243
- - `reverse()` - Reverse string
244
- - `escape()` / `unescape()` - HTML/special char handling
245
- - `slugify()` - URL-safe slug generation
246
-
247
- **Example Usage**:
248
- ```typescript
249
- capitalize('hello'); // 'Hello'
250
- toCamelCase('hello-world'); // 'helloWorld'
251
- truncate('Long text here', 10); // 'Long te...'
252
- ```
253
-
254
- ---
255
-
256
- ### 6. Date Formatter (`date-formatter.ts`)
257
-
258
- **Purpose**: Date and time formatting utilities
259
-
260
- **Key Functions**:
261
- - `formatDate()` - Format date with patterns
262
- - `formatTime()` - Format time strings
263
- - `parseDate()` - Parse date strings
264
- - `addDays()` / `addHours()` / `addMinutes()` - Date arithmetic
265
- - `getDayOfWeek()` - Get day name
266
- - `isWeekend()` / `isWorkday()` - Day classification
267
- - `getWeekNumber()` - ISO week number
268
- - `getDuration()` - Time duration calculation
269
-
270
- **Example Usage**:
271
- ```typescript
272
- formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss');
273
- addDays(new Date(), 7);
274
- const duration = getDuration(start, end); // { days: 1, hours: 2, minutes: 30 }
275
- ```
276
-
277
- ---
278
-
279
- ### 7. JSON Formatter (`json-formatter.ts`)
280
-
281
- **Purpose**: JSON processing, validation, and formatting
282
-
283
- **Key Functions**:
284
- - `parseJSON()` - Safe JSON parsing
285
- - `stringifyJSON()` - Safe JSON stringification
286
- - `formatJSON()` - Pretty print with indentation
287
- - `minifyJSON()` - Remove whitespace
288
- - `validateJSON()` - Validate JSON structure
289
- - `mergeJSON()` - Deep merge JSON objects
290
- - `flattenJSON()` - Flatten nested structures
291
- - `unflattenJSON()` - Restore nested structure
292
-
293
- **Example Usage**:
294
- ```typescript
295
- const [data, error] = parseJSON('{"name":"John"}');
296
- const pretty = formatJSON(obj, 2);
297
- const merged = mergeJSON(obj1, obj2);
298
- const flat = flattenJSON({ a: { b: { c: 1 } } }); // { 'a.b.c': 1 }
299
- ```
300
-
301
- ---
302
-
303
- ### 8. Color Formatter (`color-formatter.ts`)
304
-
305
- **Purpose**: Color processing and format conversion
306
-
307
- **Key Functions**:
308
- - `hexToRgb()` / `rgbToHex()` - Color conversion
309
- - `rgbToHsl()` / `hslToRgb()` - HSL conversion
310
- - `lighten()` / `darken()` - Color brightness
311
- - `saturate()` / `desaturate()` - Color saturation
312
- - `invertColor()` - Color inversion
313
- - `getContrast()` - WCAG contrast ratio
314
- - `isValidColor()` - Color validation
315
- - `toHex()` / `toRgb()` / `toHsl()` - Unified conversion
316
-
317
- **Example Usage**:
318
- ```typescript
319
- hexToRgb('#FF0000'); // { r: 255, g: 0, b: 0 }
320
- lighten('#FF0000', 0.2); // Lighter red
321
- getContrast('#FFFFFF', '#000000'); // 21 (WCAG AAA)
322
- ```
323
-
324
- ---
325
-
326
- ### 9. Markdown Formatter (`markdown-formatter.ts`)
327
-
328
- **Purpose**: Markdown parsing, generation, and processing
329
-
330
- **Key Functions**:
331
- - `parseMarkdown()` - Parse markdown to AST
332
- - `generateMarkdown()` - Generate markdown from AST
333
- - `extractHeadings()` - Extract heading hierarchy
334
- - `tableOfContents()` - Generate TOC
335
- - `linkValidator()` - Validate markdown links
336
- - `sanitizeMarkdown()` - Remove dangerous content
337
- - `markdownToHtml()` - Convert to HTML
338
- - `htmlToMarkdown()` - Convert from HTML
339
-
340
- **Example Usage**:
341
- ```typescript
342
- const toc = tableOfContents(markdown);
343
- const headings = extractHeadings(markdown);
344
- const html = markdownToHtml(markdown);
345
- ```
346
-
347
- ---
348
-
349
- ### 10. Image Operations
350
-
351
- #### Image Convert (`image-convert.ts`)
352
- - `convertFormat()` - Convert image formats (PNG, JPG, WEBP)
353
- - `detectFormat()` - Detect image format
354
- - `optimizeImage()` - Reduce file size
355
- - `getImageDimensions()` - Get width/height
356
-
357
- #### Image Resize (`image-resize.ts`)
358
- - `resizeImage()` - Resize with options
359
- - `fitImage()` - Fit to bounds
360
- - `cropImage()` - Crop region
361
- - `rotateImage()` - Rotate degrees
362
- - `thumbnailImage()` - Generate thumbnail
363
-
364
- #### Clipboard Image (`clipboard-image.ts`)
365
- - `copyImageToClipboard()` - Copy image from path
366
- - `pasteImageFromClipboard()` - Get image from clipboard
367
- - `captureScreenshot()` - Capture screen region
368
- - `saveClipboardImage()` - Save clipboard image to file
369
-
370
- #### Photon (`photon.ts`)
371
- - `applyFilter()` - Apply image filters
372
- - `adjustBrightness()` - Brightness control
373
- - `adjustContrast()` - Contrast control
374
- - `applyBlur()` - Gaussian blur
375
- - `sharpenImage()` - Sharpening effect
376
-
377
- **Example Usage**:
378
- ```typescript
379
- const resized = await resizeImage('./image.jpg', { width: 800, height: 600 });
380
- const thumbnail = await thumbnailImage('./large.jpg', 200);
381
- const converted = await convertFormat('./image.png', 'webp', { quality: 0.8 });
382
- ```
383
-
384
- ---
385
-
386
- ### 11. Git Operations (`git.ts`)
387
-
388
- **Purpose**: Git command wrapper and repository operations
389
-
390
- **Key Functions**:
391
- - `getGitStatus()` - Get repository status
392
- - `getCommitHistory()` - Retrieve commit log
393
- - `getCurrentBranch()` - Get active branch
394
- - `getRemotes()` - List remotes
395
- - `getGitRoot()` - Find repository root
396
- - `getAuthorInfo()` - Get author configuration
397
- - `checkIsRepository()` - Verify git repo
398
- - `getGitVersion()` - Get git version
399
-
400
- **Example Usage**:
401
- ```typescript
402
- const status = await getGitStatus();
403
- const history = await getCommitHistory(10); // Last 10 commits
404
- const branch = await getCurrentBranch();
405
- ```
406
-
407
- ---
408
-
409
- ### 12. Clipboard Operations (`clipboard.ts`)
410
-
411
- **Purpose**: Read/write to system clipboard
412
-
413
- **Key Functions**:
414
- - `readClipboard()` - Read clipboard text
415
- - `writeClipboard()` - Write clipboard text
416
- - `clearClipboard()` - Clear clipboard
417
- - `getClipboardHistory()` - Clipboard history
418
- - `isClipboardAvailable()` - Check availability
419
-
420
- **Example Usage**:
421
- ```typescript
422
- const text = await readClipboard();
423
- await writeClipboard('Copied text');
424
- ```
425
-
426
- ---
427
-
428
- ### 13. Changelog (`changelog.ts`)
429
-
430
- **Purpose**: Changelog parsing and generation
431
-
432
- **Key Functions**:
433
- - `parseChangelog()` - Parse CHANGELOG.md
434
- - `generateChangelog()` - Create from commits
435
- - `formatVersion()` - Format version entries
436
- - `addEntry()` - Add changelog entry
437
- - `getLatestVersion()` - Get latest version
438
- - `getVersionHistory()` - All versions
439
-
440
- **Example Usage**:
441
- ```typescript
442
- const changelog = await parseChangelog();
443
- const latest = getLatestVersion(changelog);
444
- const entry = addEntry(changelog, '1.2.0', { features: ['New feature'] });
445
- ```
446
-
447
- ---
448
-
449
- ### 14. Data Transformer (`data-transformer.ts`)
450
-
451
- **Purpose**: Data transformation and pipeline utilities
452
-
453
- **Key Functions**:
454
- - `transform()` - Transform data through pipeline
455
- - `map()` - Transform each item
456
- - `filter()` - Filter items
457
- - `reduce()` - Reduce to single value
458
- - `batch()` - Process in batches
459
- - `parallel()` - Parallel processing
460
- - `chain()` - Chain transformations
461
-
462
- **Example Usage**:
463
- ```typescript
464
- const result = await transform(data)
465
- .pipe(filter(x => x.active))
466
- .pipe(map(x => x.value))
467
- .pipe(reduce((a, b) => a + b, 0))
468
- .execute();
469
- ```
470
-
471
- ---
472
-
473
- ### 15. YAML Frontmatter (`frontmatter.ts`)
474
-
475
- **Purpose**: Parse and manipulate YAML frontmatter in files
476
-
477
- **Key Functions**:
478
- - `parseFrontmatter()` - Extract frontmatter and content
479
- - `stringifyFrontmatter()` - Create file with frontmatter
480
- - `updateFrontmatter()` - Update frontmatter properties
481
- - `getFrontmatterValue()` - Get specific value
482
- - `validateFrontmatter()` - Validate structure
483
-
484
- **Example Usage**:
485
- ```typescript
486
- const { frontmatter, content } = parseFrontmatter(fileContent);
487
- const updated = updateFrontmatter(fileContent, { title: 'New Title' });
488
- ```
489
-
490
- ---
491
-
492
- ### 16. MIME Type Detection (`mime.ts`)
493
-
494
- **Purpose**: MIME type detection and mapping
495
-
496
- **Key Functions**:
497
- - `getMimeType()` - Get MIME type from extension
498
- - `getExtension()` - Get extension from MIME type
499
- - `isMimeType()` - Check MIME type
500
- - `getCategory()` - Categorize MIME type
501
- - `isText()` / `isImage()` / `isVideo()` - Type checking
502
-
503
- **Example Usage**:
504
- ```typescript
505
- getMimeType('.jpg'); // 'image/jpeg'
506
- getExtension('text/plain'); // '.txt'
507
- isImage('image/png'); // true
508
- ```
509
-
510
- ---
511
-
512
- ### 17. Path Validator (`path-validator.ts`)
513
-
514
- **Purpose**: Path validation and resolution utilities
515
-
516
- **Key Functions**:
517
- - `validatePath()` - Validate path format
518
- - `resolvePath()` - Resolve relative/absolute paths
519
- - `normalizePath()` - Normalize path separators
520
- - `isAbsolute()` / `isRelative()` - Path type checking
521
- - `joinPaths()` - Join path segments
522
- - `getPathParts()` - Extract path components
523
- - `isSafePath()` - Check security
524
-
525
- **Example Usage**:
526
- ```typescript
527
- const safe = validatePath('./src/utils');
528
- const absolute = resolvePath('../config.json');
529
- const joined = joinPaths('src', 'utils', 'array.ts');
530
- ```
531
-
532
- ---
533
-
534
- ### 18. Shell Operations (`shell.ts`)
535
-
536
- **Purpose**: Safe shell command execution
537
-
538
- **Key Functions**:
539
- - `executeCommand()` - Run shell commands
540
- - `executeCommandAsync()` - Async command execution
541
- - `executeWithPipe()` - Pipe commands
542
- - `checkCommand()` - Check command availability
543
- - `shellEscape()` - Escape shell arguments
544
-
545
- **Example Usage**:
546
- ```typescript
547
- const result = await executeCommand('npm --version');
548
- const output = result.stdout;
549
-
550
- const piped = await executeWithPipe('cat file.txt | grep pattern');
551
- ```
552
-
553
- ---
554
-
555
- ### 19. Sleep Utilities (`sleep.ts`)
556
-
557
- **Purpose**: Timing and delay utilities
558
-
559
- **Key Functions**:
560
- - `sleep()` - Simple delay
561
- - `delay()` - Delay with callback
562
- - `timeout()` - Timeout wrapper
563
- - `debounce()` - Debounce function calls
564
- - `throttle()` - Throttle function calls
565
-
566
- **Example Usage**:
567
- ```typescript
568
- await sleep(1000); // Wait 1 second
569
- const debounced = debounce(handleChange, 300);
570
- const throttled = throttle(handleScroll, 100);
571
- ```
572
-
573
- ---
574
-
575
- ### 20. Type Guards (`type-guards.ts`)
576
-
577
- **Purpose**: Runtime type checking utilities
578
-
579
- **Key Functions**:
580
- - `isString()` / `isNumber()` / `isBoolean()` - Primitive checks
581
- - `isArray()` / `isObject()` / `isFunction()` - Type checks
582
- - `isNull()` / `isUndefined()` / `isDefined()` - Null checks
583
- - `isDate()` / `isRegExp()` / `isPromise()` - Special types
584
- - `isPlainObject()` - Check plain object
585
- - `hasProperty()` / `hasMethod()` - Property checks
586
- - `assertType()` - Throw if type mismatch
587
-
588
- **Example Usage**:
589
- ```typescript
590
- if (isArray(value)) { /* ... */ }
591
- if (isDefined(value) && isString(value)) { /* ... */ }
592
- assertType(value, 'string');
593
- ```
594
-
595
- ---
596
-
597
- ### 21. Tools Manager (`tools-manager.ts`)
598
-
599
- **Purpose**: Tool registry and lifecycle management
600
-
601
- **Key Functions**:
602
- - `registerTool()` - Register tool
603
- - `getTool()` - Retrieve tool
604
- - `listTools()` - List all tools
605
- - `enableTool()` / `disableTool()` - Control tools
606
- - `executeTool()` - Run tool
607
- - `validateTool()` - Validate tool
608
-
609
- **Example Usage**:
610
- ```typescript
611
- registerTool('logger', loggerTool);
612
- const tool = getTool('logger');
613
- const result = await executeTool('logger', { level: 'info' });
614
- ```
615
-
616
- ---
617
-
618
- ## Utility Categories
619
-
620
- ### Data Processing (9)
621
- 1. Array - Array manipulation
622
- 2. String Formatter - String operations
623
- 3. Color Formatter - Color processing
624
- 4. JSON Formatter - JSON processing
625
- 5. Data Transformer - Transformation pipeline
626
- 6. Frontmatter - YAML handling
627
- 7. Markdown Formatter - Markdown processing
628
- 8. Date Formatter - Date/time operations
629
- 9. MIME - MIME type detection
630
-
631
- ### File & System (7)
632
- 1. File Operations - File I/O
633
- 2. Path Validator - Path handling
634
- 3. Shell - Command execution
635
- 4. Git - Git operations
636
- 5. Clipboard - Clipboard access
637
- 6. Changelog - Changelog management
638
- 7. Sleep - Timing utilities
639
-
640
- ### Image Processing (5)
641
- 1. Image Convert - Format conversion
642
- 2. Image Resize - Resizing operations
643
- 3. Image Photon - Filters & effects
644
- 4. Clipboard Image - Image clipboard
645
- 5. Color Formatter - Color utilities
646
-
647
- ### Infrastructure (3)
648
- 1. Logger - Structured logging
649
- 2. Error Handler - Error handling
650
- 3. Type Guards - Type checking
651
-
652
- ### Tools & Registry (1)
653
- 1. Tools Manager - Tool management
654
-
655
- ---
656
-
657
- ## Quick Reference Table
658
-
659
- | Utility | Purpose | Key Functions | Files | Lines |
660
- |---------|---------|---------------|-------|-------|
661
- | array.ts | Array manipulation | groupBy, unique, flatten, chunk, sort | 25+ | 600+ |
662
- | error-handler.ts | Error handling | formatError, sanitize, retry | 8 | 500+ |
663
- | logger.ts | Structured logging | createLogger, setLevel, time | 8 | 450+ |
664
- | file-operations.ts | File I/O | read, write, list, delete | 15+ | 550+ |
665
- | string-formatter.ts | String utils | capitalize, case, truncate | 12+ | 400+ |
666
- | date-formatter.ts | Date utils | format, parse, add, duration | 10+ | 350+ |
667
- | json-formatter.ts | JSON utils | parse, stringify, merge, flatten | 8 | 400+ |
668
- | color-formatter.ts | Color utils | convert, lighten, contrast | 12+ | 400+ |
669
- | markdown-formatter.ts | Markdown | parse, generate, TOC, sanitize | 10+ | 450+ |
670
- | image-convert.ts | Image convert | convert, detect, optimize | 6 | 300+ |
671
- | image-resize.ts | Image resize | resize, crop, rotate | 8 | 350+ |
672
- | clipboard-image.ts | Image clipboard | copy, paste, capture | 6 | 300+ |
673
- | photon.ts | Image filters | filters, brightness, contrast, blur | 12+ | 400+ |
674
- | git.ts | Git operations | status, history, branch, author | 10+ | 400+ |
675
- | clipboard.ts | Clipboard | read, write, clear, history | 5 | 250+ |
676
- | changelog.ts | Changelog | parse, generate, version | 8 | 350+ |
677
- | data-transformer.ts | Transform pipeline | transform, map, filter, reduce | 8 | 350+ |
678
- | frontmatter.ts | YAML frontmatter | parse, stringify, update | 6 | 300+ |
679
- | mime.ts | MIME detection | getMimeType, getExtension | 6 | 250+ |
680
- | path-validator.ts | Path utils | validate, resolve, normalize | 10+ | 350+ |
681
- | shell.ts | Shell execution | execute, async, pipe, escape | 6 | 300+ |
682
- | sleep.ts | Timing | sleep, delay, debounce, throttle | 6 | 250+ |
683
- | type-guards.ts | Type checking | isString, isArray, assertType | 20+ | 350+ |
684
- | tools-manager.ts | Tool registry | register, get, execute, validate | 8 | 300+ |
685
-
686
- ---
687
-
688
- ## Common Patterns
689
-
690
- ### Error Handling Pattern
691
-
692
- ```typescript
693
- // Pattern 1: Try-Catch with Formatting
694
- try {
695
- const result = await operation();
696
- return result;
697
- } catch (error) {
698
- const formatted = formatErrorForUser(error);
699
- console.error(formatted.message);
700
- console.error('Suggestions:', formatted.suggestions);
701
- throw error;
702
- }
703
-
704
- // Pattern 2: Promise Wrapper (Go-style)
705
- const [data, error] = await handlePromise(fetch('/api/data'));
706
- if (error) {
707
- const formatted = formatErrorForUser(error);
708
- return { success: false, error: formatted };
709
- }
710
- return { success: true, data };
711
-
712
- // Pattern 3: Retry with Backoff
713
- const data = await retryWithBackoff(
714
- () => fetch('/api/data').then(r => r.json()),
715
- 3,
716
- 1000
717
- );
718
- ```
719
-
720
- ### Logging Pattern
721
-
722
- ```typescript
723
- // Pattern 1: Module Logger
724
- const log = createLogger('ModuleName');
725
- log.info('Operation started', { userId: 42 });
726
- log.error('Failed', { error: error.message });
727
-
728
- // Pattern 2: Performance Monitoring
729
- const timer = log.time('database-query');
730
- const result = await db.query('SELECT *');
731
- timer(); // Logs: "database-query: 25ms"
732
-
733
- // Pattern 3: Scoped Context
734
- const requestLog = createScopedLogger(log, 'req-123', { userId: 42 });
735
- requestLog.info('Processing'); // Includes userId automatically
736
- ```
737
-
738
- ### Transformation Pipeline
739
-
740
- ```typescript
741
- const result = await transform(users)
742
- .pipe(filter(u => u.active))
743
- .pipe(map(u => ({ ...u, name: u.name.toUpperCase() })))
744
- .pipe(sortBy(u => u.name))
745
- .pipe(chunk(10))
746
- .execute();
747
- ```
748
-
749
- ### File Operations Pattern
750
-
751
- ```typescript
752
- // Pattern 1: Safe Read-Process-Write
753
- const content = await readFile('./input.json');
754
- const data = JSON.parse(content);
755
- const processed = processData(data);
756
- await writeFile('./output.json', JSON.stringify(processed, null, 2), {
757
- createDirs: true
758
- });
759
-
760
- // Pattern 2: Batch Processing
761
- const count = await batchProcessFiles(
762
- './src',
763
- async (filePath) => {
764
- const content = await readFile(filePath);
765
- await processFile(content);
766
- },
767
- { extension: '.ts', recursive: true }
768
- );
769
- ```
770
-
771
- ---
772
-
773
- ## Error Handling Best Practices
774
-
775
- ### 1. Always Format Errors for Users
776
-
777
- ```typescript
778
- // BAD: Shows technical details
779
- catch (error) {
780
- console.error(error.message);
781
- }
782
-
783
- // GOOD: User-friendly with suggestions
784
- catch (error) {
785
- const formatted = formatErrorForUser(error);
786
- showNotification({
787
- title: 'Operation Failed',
788
- message: formatted.message,
789
- suggestions: formatted.suggestions
790
- });
791
- }
792
- ```
793
-
794
- ### 2. Sanitize Messages Before Display
795
-
796
- ```typescript
797
- // BAD: May leak sensitive info
798
- const message = error.message; // Could contain paths, tokens
799
-
800
- // GOOD: Sanitized safe message
801
- const message = sanitizeErrorMessage(error.message);
802
- // Removes: paths, URLs, credentials, env vars
803
- ```
804
-
805
- ### 3. Use Proper Error Codes
806
-
807
- ```typescript
808
- // BAD: Generic error handling
809
- if (error) console.error('Error');
810
-
811
- // GOOD: Categorized error handling
812
- try {
813
- await fileOp();
814
- } catch (error) {
815
- let code = 'UNKNOWN';
816
- if (error.message.includes('ENOENT')) code = 'ENOENT';
817
- else if (error.message.includes('EACCES')) code = 'EACCES';
818
-
819
- const formatted = formatErrorForUser(error, { code });
820
- // Show appropriate UI based on code
821
- }
822
- ```
823
-
824
- ### 4. Log Technical Details Separately
825
-
826
- ```typescript
827
- try {
828
- await operation();
829
- } catch (error) {
830
- const formatted = formatErrorForUser(error);
831
-
832
- // Log full technical details (never shown to user)
833
- internalLogger.error(formatted.technicalDetails);
834
-
835
- // Show safe user message
836
- userNotification.error(formatted.message);
837
- }
838
- ```
839
-
840
- ### 5. Implement Retry Logic
841
-
842
- ```typescript
843
- // Pattern: Retry for transient failures
844
- try {
845
- return await retryWithBackoff(
846
- () => fetch('/api/data').then(r => r.json()),
847
- 3, // max attempts
848
- 1000 // base delay ms
849
- );
850
- } catch (error) {
851
- // Final error after all retries failed
852
- const formatted = formatErrorForUser(error);
853
- showFatalError(formatted);
854
- }
855
- ```
856
-
857
- ---
858
-
859
- ## Performance Guidelines
860
-
861
- ### Array Operations
862
-
863
- | Operation | Complexity | Notes | When to Use |
864
- |-----------|-----------|-------|-----------|
865
- | groupBy | O(n) | Single pass | Categorizing data |
866
- | unique | O(n) | Uses Set | Remove duplicates |
867
- | flatten | O(n) | Recursive | Normalize structure |
868
- | chunk | O(n) | Memory efficient | Batch processing |
869
- | sortBy | O(n log n) | Array copy | Ordered results |
870
- | partition | O(n) | Single pass | Split by criteria |
871
- | zip/unzip | O(n) | Single pass | Pair arrays |
872
-
873
- ### File Operations
874
-
875
- | Operation | Performance | Best For |
876
- |-----------|-----------|----------|
877
- | readFile | I/O bound | < 100 MB files |
878
- | listFiles recursive | I/O bound | Use with caution on large trees |
879
- | batch processing | I/O bound | Process multiple files sequentially |
880
- | copyFile verify | I/O bound + Hash | Critical files |
881
-
882
- ### Optimization Tips
883
-
884
- 1. **Array Operations**: Reuse results, avoid multiple passes
885
- ```typescript
886
- // BAD: Multiple passes
887
- const filtered = data.filter(x => x.active);
888
- const grouped = groupBy(filtered, x => x.role);
889
- const mapped = grouped.map(x => x.value);
890
-
891
- // GOOD: Pipeline or single operation
892
- const result = await transform(data)
893
- .pipe(filter(x => x.active))
894
- .pipe(map(x => ({ ...x, role: x.role.toUpperCase() })))
895
- .execute();
896
- ```
897
-
898
- 2. **File I/O**: Batch operations when possible
899
- ```typescript
900
- // BAD: Multiple operations
901
- for (const file of files) {
902
- const meta = await getMetadata(file);
903
- }
904
-
905
- // GOOD: Batch with iterator
906
- const count = await batchProcessFiles(dir, async (file) => {
907
- const meta = await getMetadata(file);
908
- }, { recursive: true });
909
- ```
910
-
911
- 3. **Logging**: Use appropriate levels
912
- ```typescript
913
- // BAD: Expensive operation always runs
914
- log.debug('User data: ' + JSON.stringify(hugeObject));
915
-
916
- // GOOD: Only runs if debug is enabled
917
- if (getLogLevel() <= LogLevel.DEBUG) {
918
- log.debug('User data', hugeObject);
919
- }
920
- ```
921
-
922
- 4. **String Operations**: Use efficient methods
923
- ```typescript
924
- // BAD: Multiple operations
925
- const result = str.toLowerCase().trim().split(' ').join('-');
926
-
927
- // GOOD: Direct formatting
928
- const result = stringFormatter.toKebabCase(str.trim());
929
- ```
930
-
931
- ---
932
-
933
- ## Security Considerations
934
-
935
- ### 1. Path Traversal Prevention
936
-
937
- ```typescript
938
- // BAD: Unsafe path handling
939
- const userPath = req.query.file;
940
- const content = await readFile(`./uploads/${userPath}`);
941
- // User could request: "../../../etc/passwd"
942
-
943
- // GOOD: Validate path safety
944
- const userPath = validatePath(req.query.file);
945
- if (!isSafePath(userPath)) {
946
- throw new Error('Invalid path');
947
- }
948
- const content = await readFile(`./uploads/${userPath}`);
949
- ```
950
-
951
- ### 2. Command Injection Prevention
952
-
953
- ```typescript
954
- // BAD: Shell injection vulnerability
955
- const result = await executeCommand(`rm -rf ${userDir}`);
956
- // User provides: ".; cat /etc/passwd"
957
-
958
- // GOOD: Proper escaping
959
- const result = await executeCommand('rm', ['-rf', userDir]);
960
- // Or use shell escape
961
- const command = `rm -rf ${shellEscape(userDir)}`;
962
- ```
963
-
964
- ### 3. Error Information Leakage
965
-
966
- ```typescript
967
- // BAD: Exposes internal paths
968
- catch (error) {
969
- res.json({ error: error.message });
970
- }
971
- // Client sees: "/home/user/app/src/db/connection.ts:42"
972
-
973
- // GOOD: Sanitize before sending
974
- catch (error) {
975
- const formatted = formatErrorForUser(error);
976
- res.json({ error: formatted.message });
977
- // Client sees: "Database connection failed"
978
- // Internal log: "TypeError: Cannot read property..."
979
- }
980
- ```
981
-
982
- ### 4. Clipboard Security
983
-
984
- ```typescript
985
- // Only request clipboard when necessary
986
- const permission = await navigator.permissions.query({ name: 'clipboard-read' });
987
- if (permission.state === 'granted') {
988
- const data = await readClipboard();
989
- }
990
-
991
- // Clear sensitive clipboard data
992
- await copyImageToClipboard(sensitiveImage);
993
- // Later...
994
- await clearClipboard();
995
- ```
996
-
997
- ### 5. Frontmatter Validation
998
-
999
- ```typescript
1000
- // Bad: Accept any YAML
1001
- const { frontmatter } = parseFrontmatter(userFile);
1002
- const title = frontmatter.title; // Could contain malicious code
1003
-
1004
- // Good: Validate structure
1005
- const { frontmatter } = parseFrontmatter(userFile);
1006
- validateFrontmatter(frontmatter, {
1007
- title: { type: 'string', maxLength: 200 },
1008
- author: { type: 'string', maxLength: 100 },
1009
- tags: { type: 'array', maxItems: 10 }
1010
- });
1011
- ```
1012
-
1013
- ### 6. File Size Limits
1014
-
1015
- ```typescript
1016
- // Prevent resource exhaustion
1017
- const content = await readFile(filePath, {
1018
- maxSize: 10 * 1024 * 1024 // 10 MB limit
1019
- });
1020
-
1021
- // Check before processing
1022
- const meta = await getMetadata(filePath);
1023
- if (meta.size > MAX_SAFE_SIZE) {
1024
- throw new Error('File too large');
1025
- }
1026
- ```
1027
-
1028
- ---
1029
-
1030
- ## Quick Start Examples
1031
-
1032
- ### Example 1: Complete Error Handling
1033
-
1034
- ```typescript
1035
- import {
1036
- formatErrorForUser,
1037
- sanitizeErrorMessage,
1038
- retryWithBackoff,
1039
- ErrorCode
1040
- } from './utils';
1041
-
1042
- async function fetchWithErrorHandling() {
1043
- try {
1044
- const data = await retryWithBackoff(
1045
- () => fetch('/api/data').then(r => r.json()),
1046
- 3,
1047
- 1000
1048
- );
1049
- return { success: true, data };
1050
- } catch (error) {
1051
- const formatted = formatErrorForUser(error, {
1052
- code: ErrorCode.NETWORK
1053
- });
1054
- return {
1055
- success: false,
1056
- error: formatted.message,
1057
- suggestions: formatted.suggestions
1058
- };
1059
- }
1060
- }
1061
- ```
1062
-
1063
- ### Example 2: File Processing with Logging
1064
-
1065
- ```typescript
1066
- import {
1067
- createLogger,
1068
- readFile,
1069
- writeFile,
1070
- batchProcessFiles,
1071
- formatErrorForUser
1072
- } from './utils';
1073
-
1074
- const log = createLogger('FileProcessor');
1075
-
1076
- async function processMarkdownFiles() {
1077
- try {
1078
- const timer = log.time('processing');
1079
-
1080
- let processed = 0;
1081
- const count = await batchProcessFiles(
1082
- './docs',
1083
- async (filePath) => {
1084
- try {
1085
- const content = await readFile(filePath);
1086
- const processed = processMarkdown(content);
1087
- await writeFile(filePath, processed, { createDirs: true });
1088
- log.debug('Processed file', { file: filePath });
1089
- processed++;
1090
- } catch (error) {
1091
- log.error('Failed processing file', { file: filePath, error: String(error) });
1092
- }
1093
- },
1094
- { extension: '.md', recursive: true }
1095
- );
1096
-
1097
- timer(); // Logs duration
1098
- log.info('Processing complete', { filesProcessed: processed, total: count });
1099
- } catch (error) {
1100
- const formatted = formatErrorForUser(error);
1101
- log.fatal('Batch processing failed', { error: formatted.message });
1102
- throw error;
1103
- }
1104
- }
1105
- ```
1106
-
1107
- ### Example 3: Data Transformation Pipeline
1108
-
1109
- ```typescript
1110
- import {
1111
- transform,
1112
- createLogger,
1113
- groupBy,
1114
- formatDate
1115
- } from './utils';
1116
-
1117
- const log = createLogger('Analytics');
1118
-
1119
- async function analyzeUserActivity() {
1120
- const result = await transform(userEvents)
1121
- .pipe(filter(e => e.timestamp > oneWeekAgo))
1122
- .pipe(map(e => ({
1123
- userId: e.userId,
1124
- action: e.action.toUpperCase(),
1125
- date: formatDate(new Date(e.timestamp), 'yyyy-MM-dd')
1126
- })))
1127
- .pipe(groupBy(e => e.userId))
1128
- .execute();
1129
-
1130
- log.info('Analysis complete', { uniqueUsers: Object.keys(result).length });
1131
- return result;
1132
- }
1133
- ```
1134
-
1135
- ### Example 4: Git Repository Analysis
1136
-
1137
- ```typescript
1138
- import {
1139
- createLogger,
1140
- getCommitHistory,
1141
- getCurrentBranch,
1142
- getGitStatus
1143
- } from './utils';
1144
-
1145
- const log = createLogger('GitAnalysis');
1146
-
1147
- async function analyzeRepository() {
1148
- try {
1149
- const branch = await getCurrentBranch();
1150
- const status = await getGitStatus();
1151
- const history = await getCommitHistory(50);
1152
-
1153
- log.info('Repository analysis', {
1154
- branch,
1155
- uncommittedChanges: status.unstaged.length,
1156
- recentCommits: history.length
1157
- });
1158
-
1159
- return { branch, status, history };
1160
- } catch (error) {
1161
- log.error('Git operation failed', { error: String(error) });
1162
- throw error;
1163
- }
1164
- }
1165
- ```
1166
-
1167
- ### Example 5: Image Processing Pipeline
1168
-
1169
- ```typescript
1170
- import {
1171
- resizeImage,
1172
- convertFormat,
1173
- createLogger,
1174
- formatErrorForUser
1175
- } from './utils';
1176
-
1177
- const log = createLogger('ImageProcessor');
1178
-
1179
- async function optimizeImage(inputPath, outputPath) {
1180
- try {
1181
- const timer = log.time('optimization');
1182
-
1183
- // Resize to max 2048 width
1184
- const resized = await resizeImage(inputPath, {
1185
- width: 2048,
1186
- height: 2048,
1187
- fit: 'inside'
1188
- });
1189
-
1190
- // Convert to WebP for better compression
1191
- const optimized = await convertFormat(resized, 'webp', {
1192
- quality: 0.8
1193
- });
1194
-
1195
- // Save result
1196
- await writeFile(outputPath, optimized);
1197
-
1198
- timer(); // Logs duration
1199
- log.info('Image optimized', {
1200
- from: inputPath,
1201
- to: outputPath
1202
- });
1203
- } catch (error) {
1204
- const formatted = formatErrorForUser(error);
1205
- log.error('Optimization failed', { error: formatted.message });
1206
- throw error;
1207
- }
1208
- }
1209
- ```
1210
-
1211
- ---
1212
-
1213
- ## Troubleshooting Guide
1214
-
1215
- ### Common Issues
1216
-
1217
- #### 1. File Not Found Errors
1218
-
1219
- **Problem**: FileOperationError with ENOENT code
1220
-
1221
- **Root Causes**:
1222
- - File path is incorrect
1223
- - File deleted before operation
1224
- - Relative path resolving differently
1225
- - Permission issues
1226
-
1227
- **Solutions**:
1228
- ```typescript
1229
- // Solution 1: Validate path
1230
- const safePath = validatePath(filePath);
1231
-
1232
- // Solution 2: Resolve to absolute
1233
- const absolute = resolvePath(filePath);
1234
- const exists = await fileExists(absolute);
1235
-
1236
- // Solution 3: Create dirs before write
1237
- await writeFile(filePath, content, { createDirs: true });
1238
-
1239
- // Solution 4: Better error handling
1240
- try {
1241
- const content = await readFile(filePath);
1242
- } catch (error) {
1243
- if (error.code === ErrorCode.ENOENT) {
1244
- console.log('File not found. Creating template...');
1245
- await writeFile(filePath, defaultContent, { createDirs: true });
1246
- }
1247
- }
1248
- ```
1249
-
1250
- #### 2. Permission Denied Errors
1251
-
1252
- **Problem**: FileOperationError with EACCES code
1253
-
1254
- **Root Causes**:
1255
- - Insufficient file permissions
1256
- - Operating system restrictions
1257
- - Running as wrong user
1258
-
1259
- **Solutions**:
1260
- ```typescript
1261
- // Solution 1: Check permissions
1262
- const meta = await getMetadata(filePath);
1263
- const isReadable = (meta.mode & 0o400) !== 0;
1264
- const isWritable = (meta.mode & 0o200) !== 0;
1265
-
1266
- // Solution 2: Use elevated privileges
1267
- // Note: Requires system configuration
1268
- const result = await executeCommand(`sudo ${command}`);
1269
-
1270
- // Solution 3: Create with proper mode
1271
- await writeFile(filePath, content, { mode: 0o644 });
1272
- ```
1273
-
1274
- #### 3. Logging Not Showing
1275
-
1276
- **Problem**: Log messages don't appear
1277
-
1278
- **Root Causes**:
1279
- - Log level set too high
1280
- - Logger not configured
1281
- - Wrong logger instance
1282
-
1283
- **Solutions**:
1284
- ```typescript
1285
- // Solution 1: Check log level
1286
- const currentLevel = getLogLevel();
1287
- if (currentLevel > LogLevel.DEBUG) {
1288
- setLogLevel('debug'); // Lower the threshold
1289
- }
1290
-
1291
- // Solution 2: Create logger properly
1292
- const log = createLogger('MyModule');
1293
- log.info('This should show');
1294
-
1295
- // Solution 3: Use createLogger consistently
1296
- // Always use named loggers, not console.log
1297
- const log = createLogger('FeatureName');
1298
- ```
1299
-
1300
- #### 4. JSON Parsing Errors
1301
-
1302
- **Problem**: JSON.parse fails or produces invalid data
1303
-
1304
- **Root Causes**:
1305
- - Malformed JSON syntax
1306
- - Encoding issues
1307
- - Data contamination
1308
-
1309
- **Solutions**:
1310
- ```typescript
1311
- // Solution 1: Use safe parsing
1312
- const [data, error] = parseJSON(jsonString);
1313
- if (error) {
1314
- console.error('Invalid JSON:', error.message);
1315
- return null;
1316
- }
1317
-
1318
- // Solution 2: Validate before parsing
1319
- const valid = validateJSON(jsonString);
1320
- if (!valid) {
1321
- console.error('JSON validation failed');
1322
- return null;
1323
- }
1324
-
1325
- // Solution 3: Format and clean
1326
- const cleaned = formatJSON(dirtyJSON);
1327
- const parsed = JSON.parse(cleaned);
1328
- ```
1329
-
1330
- #### 5. Image Processing Failures
1331
-
1332
- **Problem**: Image conversion or resizing fails
1333
-
1334
- **Root Causes**:
1335
- - Unsupported format
1336
- - Corrupted image data
1337
- - Missing dependencies
1338
-
1339
- **Solutions**:
1340
- ```typescript
1341
- // Solution 1: Validate format
1342
- const format = detectFormat(imagePath);
1343
- const supported = ['png', 'jpg', 'webp', 'gif'];
1344
- if (!supported.includes(format)) {
1345
- throw new Error(`Unsupported format: ${format}`);
1346
- }
1347
-
1348
- // Solution 2: Check dimensions
1349
- const dimensions = await getImageDimensions(imagePath);
1350
- if (dimensions.width > 10000 || dimensions.height > 10000) {
1351
- throw new Error('Image too large');
1352
- }
1353
-
1354
- // Solution 3: Try incremental resizing
1355
- const step1 = await resizeImage(input, { width: 4000 });
1356
- const step2 = await resizeImage(step1, { width: 2000 });
1357
- ```
1358
-
1359
- #### 6. Shell Command Execution Failures
1360
-
1361
- **Problem**: executeCommand throws or produces wrong output
1362
-
1363
- **Root Causes**:
1364
- - Command not in PATH
1365
- - Wrong argument format
1366
- - Permission issues
1367
- - Shell not available
1368
-
1369
- **Solutions**:
1370
- ```typescript
1371
- // Solution 1: Check command availability
1372
- const available = await checkCommand('npm');
1373
- if (!available) {
1374
- console.error('npm not found in PATH');
1375
- return;
1376
- }
1377
-
1378
- // Solution 2: Use proper escaping
1379
- const result = await executeCommand('ls', ['-la', safePath]);
1380
- // Instead of: await executeCommand(`ls -la ${userInput}`);
1381
-
1382
- // Solution 3: Check output carefully
1383
- const result = await executeCommand('npm', ['--version']);
1384
- if (result.code !== 0) {
1385
- console.error('Command failed:', result.stderr);
1386
- }
1387
- ```
1388
-
1389
- #### 7. Type Guard Failures
1390
-
1391
- **Problem**: Type guards not catching errors
1392
-
1393
- **Root Causes**:
1394
- - Using JavaScript typeof incorrectly
1395
- - Complex type structures
1396
- - Runtime type differences
1397
-
1398
- **Solutions**:
1399
- ```typescript
1400
- // Solution 1: Use provided type guards
1401
- if (isArray(value) && value.length > 0) {
1402
- // Safe to access value[0]
1403
- }
1404
-
1405
- // Solution 2: Chain type checks
1406
- if (isDefined(value) && isObject(value) && hasProperty(value, 'name')) {
1407
- console.log(value.name); // Safe
1408
- }
1409
-
1410
- // Solution 3: Use assertion
1411
- try {
1412
- assertType(value, 'string');
1413
- console.log(value.toUpperCase()); // Now safe
1414
- } catch (error) {
1415
- console.error('Type mismatch:', error.message);
1416
- }
1417
- ```
1418
-
1419
- ### Performance Issues
1420
-
1421
- #### Problem: Slow Array Operations
1422
-
1423
- ```typescript
1424
- // Bad: Multiple iterations
1425
- const filtered = data.filter(x => x.active);
1426
- const mapped = filtered.map(x => transform(x));
1427
- const sorted = mapped.sort((a, b) => a.id - b.id);
1428
-
1429
- // Good: Single pipeline
1430
- const result = await transform(data)
1431
- .pipe(filter(x => x.active))
1432
- .pipe(map(x => transform(x)))
1433
- .pipe(sortBy((a, b) => a.id - b.id))
1434
- .execute();
1435
- ```
1436
-
1437
- #### Problem: Slow File Operations
1438
-
1439
- ```typescript
1440
- // Bad: Individual operations
1441
- for (const file of files) {
1442
- const content = await readFile(file);
1443
- await processFile(content);
1444
- await writeFile(file, processed);
1445
- }
1446
-
1447
- // Good: Batch processing
1448
- await batchProcessFiles(dir, async (file) => {
1449
- const content = await readFile(file);
1450
- const processed = await processFile(content);
1451
- await writeFile(file, processed);
1452
- });
1453
- ```
1454
-
1455
- ---
1456
-
1457
- ## Resources
1458
-
1459
- ### External References
1460
- - [Node.js fs module](https://nodejs.org/api/fs.html)
1461
- - [POSIX error codes](https://nodejs.org/api/errors.html#errors_posix_error_codes)
1462
- - [TypeScript Handbook](https://www.typescriptlang.org/docs/)
1463
- - [WCAG Color Contrast](https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum)
1464
-
1465
- ### Related Documentation
1466
- - [UTILS-USAGE-GUIDE.md](./UTILS-USAGE-GUIDE.md) - Detailed usage examples
1467
- - [UTILS-QA-CHECKLIST.md](./UTILS-QA-CHECKLIST.md) - Testing and QA
1468
- - [UTILS-IMPLEMENTATION-SUMMARY.md](./UTILS-IMPLEMENTATION-SUMMARY.md) - Implementation details
1469
-
1470
- ### Source Code
1471
- - Main utilities: `src/utils/*.ts`
1472
- - Tests: `src/utils/__tests__/*.test.ts`
1473
- - Type definitions: `src/utils/*.ts` (inline)
1474
-
1475
- ---
1476
-
1477
- **Last Updated**: February 2024
1478
- **Maintained By**: Indusagi Core Team
1479
- **License**: MIT
1480
-