0
# Utilities
1
2
JSDoc provides a comprehensive set of utility modules for common operations including logging, data manipulation, debugging, and template helpers.
3
4
## Capabilities
5
6
### Logging
7
8
Central logging system with configurable levels and output formatting.
9
10
```javascript { .api }
11
/**
12
* Logger instance with level-based output
13
*/
14
const logger = {
15
/** Log levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL */
16
LEVELS: {
17
TRACE: 10;
18
DEBUG: 20;
19
INFO: 30;
20
WARN: 40;
21
ERROR: 50;
22
FATAL: 60;
23
};
24
25
/**
26
* Set the minimum logging level
27
* @param level - Logging level or level name
28
*/
29
setLevel(level: number | string): void;
30
31
/**
32
* Get current logging level
33
* @returns Current logging level
34
*/
35
getLevel(): number;
36
37
/**
38
* Log functions for each level
39
*/
40
trace(message: string, ...args: any[]): void;
41
debug(message: string, ...args: any[]): void;
42
info(message: string, ...args: any[]): void;
43
warn(message: string, ...args: any[]): void;
44
error(message: string, ...args: any[]): void;
45
fatal(message: string, ...args: any[]): void;
46
};
47
```
48
49
### Deep Object Operations
50
51
Utilities for deep copying and manipulating complex object structures.
52
53
```javascript { .api }
54
/**
55
* Deep object operations utility
56
* @param original - Original object to copy
57
* @param extra - Additional properties to merge
58
* @returns Deep copied object with merged properties
59
*/
60
function doop(original: object, extra?: object): object;
61
```
62
63
### Debug Output
64
65
Debugging utilities for safely dumping object structures to console.
66
67
```javascript { .api }
68
/**
69
* Safely dump objects to string format for debugging
70
* @param objects - Objects to dump
71
* @returns Formatted string representation
72
*/
73
function dump(objects: any[]): string;
74
```
75
76
### Error Handling
77
78
Centralized error handling and processing utilities.
79
80
```javascript { .api }
81
/**
82
* Handle errors with consistent logging and formatting
83
* @param error - Error object or message
84
* @param context - Additional context information
85
*/
86
function handle(error: Error | string, context?: string): void;
87
```
88
89
### Type Casting
90
91
Utilities for converting and casting values between types.
92
93
```javascript { .api }
94
/**
95
* Cast values to appropriate types based on JSDoc type expressions
96
* @param value - Value to cast
97
* @param type - Target type expression
98
* @returns Casted value
99
*/
100
function cast(value: any, type: string): any;
101
```
102
103
### Markdown Processing
104
105
Markdown parsing and conversion utilities for JSDoc comments.
106
107
```javascript { .api }
108
/**
109
* Parse markdown content and convert to HTML
110
* @param source - Markdown source text
111
* @returns HTML string
112
*/
113
function parse(source: string): string;
114
115
/**
116
* Get markdown renderer instance
117
* @returns Configured markdown-it renderer
118
*/
119
function getRenderer(): any;
120
```
121
122
### BOM Stripping
123
124
Utility for removing Byte Order Mark from file content.
125
126
```javascript { .api }
127
/**
128
* Strip BOM from file content
129
* @param text - File content with potential BOM
130
* @returns Content with BOM removed
131
*/
132
function strip(text: string): string;
133
```
134
135
### Template Helpers
136
137
Comprehensive template helper functions for generating documentation output.
138
139
```javascript { .api }
140
/**
141
* Template helper functions for documentation generation
142
*/
143
const templateHelper = {
144
/**
145
* Set tutorials for template use
146
* @param tutorials - Tutorial root object
147
*/
148
setTutorials(tutorials: TutorialRoot): void;
149
150
/**
151
* Convert longname to URL
152
* @param longname - Symbol longname
153
* @returns URL string
154
*/
155
longnameToUrl(longname: string): string;
156
157
/**
158
* Create link to symbol
159
* @param longname - Symbol longname
160
* @param linkText - Link display text
161
* @returns HTML link element
162
*/
163
linkto(longname: string, linkText?: string): string;
164
165
/**
166
* Make string HTML-safe
167
* @param str - String to escape
168
* @returns HTML-escaped string
169
*/
170
htmlsafe(str: string): string;
171
172
/**
173
* Resolve author links in text
174
* @param text - Text with author information
175
* @returns Text with resolved links
176
*/
177
resolveAuthorLinks(text: string): string;
178
179
/**
180
* Get CSS class name for access level
181
* @param doclet - Doclet with access information
182
* @returns CSS class string
183
*/
184
getAccessClass(doclet: Doclet): string;
185
186
/**
187
* Find doclets matching criteria
188
* @param spec - Search specification
189
* @returns Array of matching doclets
190
*/
191
find(spec: object): Doclet[];
192
193
/**
194
* Get signature for function doclet
195
* @param doclet - Function doclet
196
* @returns Function signature string
197
*/
198
getSignature(doclet: Doclet): string;
199
200
/**
201
* Get ancestors array for doclet
202
* @param doclet - Doclet to get ancestors for
203
* @returns Array of ancestor doclets
204
*/
205
getAncestors(doclet: Doclet): Doclet[];
206
207
/**
208
* Get members of specified kinds
209
* @param data - TaffyDB data collection
210
* @param kind - Member kind to filter by
211
* @returns Filtered members
212
*/
213
getMembers(data: TaffyDB, kind: string): any;
214
215
/**
216
* Get namespace signature
217
* @param doclet - Namespace doclet
218
* @returns Namespace signature string
219
*/
220
getNamespaceSignature(doclet: Doclet): string;
221
222
/**
223
* Convert scope to punctuation
224
* @param scope - Scope string
225
* @returns Punctuation character
226
*/
227
scopeToPunc(scope: string): string;
228
229
/**
230
* Register link for symbol
231
* @param longname - Symbol longname
232
* @param url - URL to register
233
*/
234
registerLink(longname: string, url: string): void;
235
236
/**
237
* Check if symbol is external
238
* @param longname - Symbol longname
239
* @returns True if external
240
*/
241
isExternal(longname: string): boolean;
242
};
243
```
244
245
### AST Node Utilities
246
247
Utilities for working with Abstract Syntax Tree nodes during parsing.
248
249
```javascript { .api }
250
/**
251
* AST node manipulation utilities
252
*/
253
const astnode = {
254
/**
255
* Get node by ID
256
* @param nodeId - Unique node identifier
257
* @returns AST node object
258
*/
259
getById(nodeId: string): ASTNode;
260
261
/**
262
* Add node to tracking system
263
* @param node - AST node to track
264
* @returns Assigned node ID
265
*/
266
addNode(node: ASTNode): string;
267
268
/**
269
* Get parent node
270
* @param node - Child node
271
* @returns Parent AST node
272
*/
273
getParent(node: ASTNode): ASTNode;
274
275
/**
276
* Check if node is of specified type
277
* @param node - AST node to check
278
* @param type - Node type string
279
* @returns True if node matches type
280
*/
281
isType(node: ASTNode, type: string): boolean;
282
};
283
```
284
285
### AST Builder
286
287
Utilities for building and manipulating Abstract Syntax Trees.
288
289
```javascript { .api }
290
/**
291
* AST building utilities
292
*/
293
const astbuilder = {
294
/**
295
* Build AST from source code
296
* @param source - JavaScript source code
297
* @param filename - Source filename
298
* @returns AST root node
299
*/
300
build(source: string, filename: string): ASTNode;
301
302
/**
303
* Add parent references to AST nodes
304
* @param node - Root AST node
305
*/
306
addParentReferences(node: ASTNode): void;
307
308
/**
309
* Add scope information to nodes
310
* @param node - Root AST node
311
*/
312
addScopes(node: ASTNode): void;
313
};
314
```
315
316
### Syntax Definitions
317
318
JavaScript syntax and parsing configuration utilities.
319
320
```javascript { .api }
321
/**
322
* JavaScript syntax configuration
323
*/
324
const syntax = {
325
/** Babel parser options for JavaScript */
326
jsParser: object;
327
328
/** File extensions to process */
329
extensions: string[];
330
331
/**
332
* Get parser options for file type
333
* @param filename - File to parse
334
* @returns Parser configuration
335
*/
336
getParserOptions(filename: string): object;
337
};
338
```
339
340
### File System Utilities
341
342
Enhanced file system operations with JSDoc-specific functionality.
343
344
```javascript { .api }
345
/**
346
* Enhanced filesystem operations
347
*/
348
const fs = {
349
/**
350
* Read file with encoding detection
351
* @param filepath - Path to file
352
* @param encoding - File encoding
353
* @returns File contents
354
*/
355
readFileSync(filepath: string, encoding?: string): string;
356
357
/**
358
* Write file with directory creation
359
* @param filepath - Path to file
360
* @param content - Content to write
361
* @param encoding - File encoding
362
*/
363
writeFileSync(filepath: string, content: string, encoding?: string): void;
364
365
/**
366
* Get file statistics
367
* @param filepath - Path to file
368
* @returns File stats object
369
*/
370
statSync(filepath: string): object;
371
372
/**
373
* List directory contents
374
* @param dirpath - Directory path
375
* @returns Array of file/directory names
376
*/
377
readdirSync(dirpath: string): string[];
378
};
379
```
380
381
### Path Utilities
382
383
Path manipulation utilities with JSDoc-specific enhancements.
384
385
```javascript { .api }
386
/**
387
* Path manipulation utilities
388
*/
389
const path = {
390
/**
391
* Normalize file paths for cross-platform compatibility
392
* @param filepath - Path to normalize
393
* @returns Normalized path
394
*/
395
normalize(filepath: string): string;
396
397
/**
398
* Join path segments
399
* @param segments - Path segments to join
400
* @returns Joined path
401
*/
402
join(...segments: string[]): string;
403
404
/**
405
* Get file extension
406
* @param filepath - File path
407
* @returns File extension including dot
408
*/
409
extname(filepath: string): string;
410
411
/**
412
* Get directory name
413
* @param filepath - File path
414
* @returns Directory path
415
*/
416
dirname(filepath: string): string;
417
418
/**
419
* Get base filename
420
* @param filepath - File path
421
* @param ext - Extension to remove
422
* @returns Base filename
423
*/
424
basename(filepath: string, ext?: string): string;
425
};
426
```
427
428
## Usage Examples
429
430
### Basic Logging
431
432
```javascript
433
const logger = require('jsdoc/util/logger');
434
435
// Set logging level
436
logger.setLevel('DEBUG');
437
438
// Log messages
439
logger.info('Starting documentation generation');
440
logger.warn('Deprecated tag usage detected');
441
logger.error('Parse error in file:', filename);
442
```
443
444
### Template Helpers
445
446
```javascript
447
const helper = require('jsdoc/util/templateHelper');
448
449
// In template publish function
450
function publish(data, opts) {
451
const classes = helper.find(data, { kind: 'class' });
452
453
classes.forEach(cls => {
454
const url = helper.longnameToUrl(cls.longname);
455
const link = helper.linkto(cls.longname, cls.name);
456
const signature = helper.getSignature(cls);
457
458
console.log(`Class: ${link} -> ${url}`);
459
});
460
}
461
```
462
463
### Deep Object Operations
464
465
```javascript
466
const doop = require('jsdoc/util/doop');
467
468
// Deep copy with additional properties
469
const originalConfig = { source: { include: ['src/'] } };
470
const modifiedConfig = doop(originalConfig, {
471
source: { exclude: ['test/'] }
472
});
473
474
// Original remains unchanged
475
console.log(originalConfig.source.exclude); // undefined
476
console.log(modifiedConfig.source.exclude); // ['test/']
477
```
478
479
### Debug Output
480
481
```javascript
482
const dumper = require('jsdoc/util/dumper');
483
484
// Safely dump complex objects
485
const complexObject = {
486
circular: null,
487
data: [1, 2, 3],
488
nested: { deep: { value: 'test' } }
489
};
490
complexObject.circular = complexObject; // Create circular reference
491
492
console.log(dumper.dump([complexObject])); // Safe output
493
```
494
495
### Markdown Processing
496
497
```javascript
498
const markdown = require('jsdoc/util/markdown');
499
500
// Process markdown in doclets
501
function processDoclet(doclet) {
502
if (doclet.description) {
503
doclet.description = markdown.parse(doclet.description);
504
}
505
506
if (doclet.summary) {
507
doclet.summary = markdown.parse(doclet.summary);
508
}
509
}
510
```
511
512
## Integration with Core Systems
513
514
### Parser Integration
515
516
Utilities are automatically available within the parser system:
517
518
```javascript
519
const parser = require('jsdoc/src/parser');
520
const logger = require('jsdoc/util/logger');
521
522
const jsdocParser = parser.createParser();
523
524
jsdocParser.on('parseBegin', (e) => {
525
logger.info(`Starting parse of ${e.sourcefiles.length} files`);
526
});
527
528
jsdocParser.on('newDoclet', (e) => {
529
if (e.doclet.undocumented) {
530
logger.warn(`Undocumented symbol: ${e.doclet.longname}`);
531
}
532
});
533
```
534
535
### Plugin Development
536
537
Utilities are essential for plugin development:
538
539
```javascript
540
// my-plugin.js
541
const logger = require('jsdoc/util/logger');
542
const helper = require('jsdoc/util/templateHelper');
543
544
exports.handlers = {
545
newDoclet: function(e) {
546
logger.debug(`Processing doclet: ${e.doclet.longname}`);
547
548
if (e.doclet.kind === 'function') {
549
const signature = helper.getSignature(e.doclet);
550
e.doclet.customSignature = signature;
551
}
552
}
553
};
554
```
555
556
### Template Development
557
558
Template helpers are the foundation of custom templates:
559
560
```javascript
561
// template publish function
562
const helper = require('jsdoc/util/templateHelper');
563
564
function publish(data, opts) {
565
// Find all documented symbols
566
const documented = helper.find(data, { undocumented: { '!is': true } });
567
568
documented.forEach(doclet => {
569
const url = helper.longnameToUrl(doclet.longname);
570
const ancestors = helper.getAncestors(doclet);
571
572
generateDocPage(doclet, url, ancestors);
573
});
574
}
575
```
576
577
## Error Handling
578
579
### Utility Error Patterns
580
581
```javascript
582
const error = require('jsdoc/util/error');
583
584
try {
585
// Risky operation
586
processDoclet(doclet);
587
} catch (e) {
588
error.handle(e, `Processing doclet: ${doclet.longname}`);
589
}
590
```
591
592
### Logging Errors
593
594
```javascript
595
const logger = require('jsdoc/util/logger');
596
597
function safeOperation(data) {
598
try {
599
return processData(data);
600
} catch (e) {
601
logger.error('Operation failed:', e.message);
602
logger.debug('Stack trace:', e.stack);
603
return null;
604
}
605
}
606
```