JSDoc Parser
A professional Python package for parsing JavaScript documentation comments (JSDoc) into structured Pydantic BaseModel objects.
Features
- Comprehensive JSDoc Support: Parses all major JSDoc tags including
@param,@returns,@typedef,@property,@example, and@throws - Multiple TypeDef Support: Parse multiple
@typedefdefinitions from single or separate comment blocks - Type-Safe: Built with Pydantic BaseModel for robust data validation and type safety
- Union Types: Full support for union types like
string|number|null - Optional Parameters: Handles optional parameters with bracket syntax
[param] - Code Extraction: Optionally extracts JavaScript code that follows JSDoc comments
- Function Name Parsing: Automatically extracts function names from various JavaScript function definitions
- Professional API: Simple
parse()function interface with detailed structured output
Installation
pip install jsdoc
Quick Start
from jsdoc import parse
# Parse a JSDoc comment
jsdoc_string = '''/**
* Adds two numbers together.
* @param {number} a - The first number
* @param {number} b - The second number
* @returns {number} The sum of a and b
* @example
* add(1, 2); // returns 3
*/
function add(a, b) {
return a + b;
}'''
result = parse(jsdoc_string)
# Access structured data
print(result.description.summary) # "Adds two numbers together."
print(result.params[0].name) # "a"
print(result.params[0].types) # ["number"]
print(result.returns[0].types) # ["number"]
print(result.examples[0].code) # "add(1, 2); // returns 3"
print(result.code) # "function add(a, b) {\\n return a + b;\\n}"
print(result.function_name) # "add"
Supported JSDoc Tags
| Tag | Description | Example |
|---|---|---|
@param |
Function parameter | @param {string} name - User's name |
@returns/@return |
Return value | @returns {number} Sum of a and b |
@typedef |
Custom type definition | @typedef {Object} User |
@property |
Object property | @property {number} age - User's age |
@example |
Usage example | @example doSomething(123); |
@throws |
Possible exceptions | @throws {Error} If input is invalid |
Output Structure
The parse() function returns a JSDocComment object with the following structure:
{
"description": {
"full": "Complete description text...",
"summary": "Brief summary sentence."
},
"params": [
{
"types": ["string"],
"name": "param_name",
"description": "Parameter description",
"optional": False
}
],
"returns": [
{
"types": ["number"],
"description": "Return value description"
}
],
"examples": [
{
"code": "example_code();",
"description": None
}
],
"throws": [
{
"types": ["Error"],
"description": "Exception description"
}
],
"typedefs": [
{
"types": ["Object"],
"name": "CustomType",
"description": "Type description",
"properties": [...]
}
],
"properties": [...],
"code": "function code() { ... }",
"function_name": "functionName",
"raw_comment": "/** original comment */"
}
Advanced Usage
Parsing Without Code Extraction
result = parse(jsdoc_string, include_code=False)
# result.code will be None
Handling TypeDefs with Properties
jsdoc = '''/**
* @typedef {object} User
* @property {string} name - User's name
* @property {number} age - User's age
* @property {string|null} email - User's email (optional)
*/'''
result = parse(jsdoc, include_code=False)
print(result.typedefs[0].name) # "User"
print(result.typedefs[0].properties[0].name) # "name"
print(result.typedefs[0].properties[0].types) # ["string"]
print(result.typedefs[0].properties[2].types) # ["string", "null"]
Multiple TypeDef Definitions
Parse multiple typedef definitions from a single comment block:
jsdoc = '''/**
* @typedef {object} User
* @property {string} name - User's name
*
* @typedef {object} Role
* @property {string} name - Role name
* @property {string[]} permissions - Role permissions
*
* @typedef {string} Status - User status
*/'''
result = parse(jsdoc, include_code=False)
print(len(result.typedefs)) # 3
print(result.typedefs[0].name) # "User"
print(result.typedefs[1].name) # "Role"
print(result.typedefs[2].name) # "Status"
Or from separate comment blocks:
jsdoc = '''/**
* @typedef {object} Product
* @property {string} id - Product identifier
* @property {number} price - Product price
*/
/**
* @typedef {object} Category
* @property {string} name - Category name
* @property {Product[]} products - Products in category
*/
function getProducts() {
return products;
}'''
result = parse(jsdoc)
print(len(result.typedefs)) # 2
print(result.typedefs[0].name) # "Product"
print(result.typedefs[1].name) # "Category"
print(result.code) # "function getProducts() { ... }"
Optional Parameters
jsdoc = '''/**
* @param {string} name - Required parameter
* @param {number} [age] - Optional parameter
* @param {string} [email=user@example.com] - Optional with default
*/'''
result = parse(jsdoc, include_code=False)
print(result.params[0].optional) # False
print(result.params[1].optional) # True
print(result.params[2].optional) # True
Union Types
jsdoc = '''/**
* @param {string|number|boolean} value - Multi-type parameter
* @returns {User|null} User object or null
*/'''
result = parse(jsdoc, include_code=False)
print(result.params[0].types) # ["string", "number", "boolean"]
print(result.returns[0].types) # ["User", "null"]
Function Name Extraction
The parser automatically extracts function names from various JavaScript function definition patterns:
# Standard function declaration
jsdoc = '''/**
* A standard function.
*/
function myFunction() {
return true;
}'''
result = parse(jsdoc)
print(result.function_name) # "myFunction"
# Arrow function
jsdoc = '''/**
* An arrow function.
*/
const arrowFunc = () => {
return "hello";
}'''
result = parse(jsdoc)
print(result.function_name) # "arrowFunc"
# Async function
jsdoc = '''/**
* An async function.
*/
async function fetchData() {
return await api.getData();
}'''
result = parse(jsdoc)
print(result.function_name) # "fetchData"
# Class method
jsdoc = '''/**
* A class method.
*/
methodName() {
return this.value;
}'''
result = parse(jsdoc)
print(result.function_name) # "methodName"
Supported function definition patterns:
function name() {}- Standard function declarationsasync function name() {}- Async function declarationsexport function name() {}- Exported functionsconst name = () => {}- Arrow functionsconst name = function() {}- Function expressionsname: function() {}- Object methodsname() {}- Object method shorthandstatic name() {}- Static class methods
API Reference
parse(jsdoc_string: str, include_code: bool = True) -> JSDocComment
Parse a JSDoc comment string into a structured object.
Parameters:
jsdoc_string(str): JSDoc comment string, typically wrapped in/** */include_code(bool): Whether to extract JavaScript code following the comment
Returns:
JSDocComment: Structured representation of the parsed JSDoc
Raises:
ValueError: If the input is not a valid JSDoc comment format
Data Models
All returned objects are Pydantic BaseModel instances with full type validation:
JSDocComment: Main container for all parsed dataDescription: Comment description with full text and summaryParameter: Function parameter informationReturnValue: Return value informationTypeDef: Custom type definitionProperty: Object property definitionExample: Usage exampleThrows: Exception information
Error Handling
The parser will raise ValueError for invalid input:
try:
result = parse("invalid comment")
except ValueError as e:
print(f"Parse error: {e}")
Development
Setup Development Environment
git clone https://github.com/yunfanye/jsdoc
cd jsdoc
pip install -e ".[dev]"
Running Tests
pytest
pytest -v # verbose output
pytest --cov=jsdoc_parser # with coverage
Code Formatting
black jsdoc_parser/
isort jsdoc_parser/
flake8 jsdoc_parser/
License
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create a feature branch
- Add tests for your changes
- Ensure all tests pass
- Submit a pull request
Changelog
v1.0.3
- NEW FEATURE: Added
function_namefield to automatically extract function names from JavaScript code - Support for robust function name extraction from various JS function definition patterns:
- Standard function declarations (
function name() {}) - Arrow functions (
const name = () => {}) - Async functions (
async function name() {}) - Exported functions (
export function name() {}) - Function expressions (
const name = function() {}) - Object methods (
name: function() {},name() {}) - Static class methods (
static name() {})
- Standard function declarations (
- Added comprehensive tests for function name extraction (23 tests total)
- Updated documentation with function name extraction examples
v1.0.2
- BREAKING CHANGE: Changed
typedeffield totypedefs(List[TypeDef]) in JSDocComment model - Added support for multiple typedef definitions in single comment block
- Added support for parsing separate typedef comment blocks
- Improved comment block selection logic for mixed typedef and function documentation
- Enhanced code extraction to work correctly with multiple comment blocks
- Added comprehensive tests for multiple typedef scenarios
- Updated documentation with multiple typedef examples
v1.0.1
- Bug fixes and improvements
v1.0.0
- Initial release
- Support for all major JSDoc tags
- Pydantic BaseModel integration
- Comprehensive test suite
- Professional documentation
Metadata
Release files for jsdoc 1.0.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| jsdoc-1.0.3.tar.gz | 20.4 kB | Without provenance | Details for jsdoc-1.0.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| jsdoc-1.0.3-py3-none-any.whl | Python 3 | none | any | Details for jsdoc-1.0.3-py3-none-any.whl |
Total release size: 31.8 kB
Release files / jsdoc-1.0.3.tar.gz
| Download URL | jsdoc-1.0.3.tar.gz |
|---|---|
| Size | 20.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2e75af4fcb8095922e0443ca2033088cb6e4316f0d468f032202964ac555513d
|
|
BLAKE2b-256 checksum How to use checksums |
015b302ed58cc04ebef273b531bac1fd3e938ed2cf44148a4e8b89bc6d086398
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.7
|
Release files / jsdoc-1.0.3-py3-none-any.whl
| Download URL | jsdoc-1.0.3-py3-none-any.whl |
|---|---|
| Size | 11.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
77c1fcc277951ebe1c28da1445f0d436aa0f4d9a86807356fce0e5c531e76e06
|
|
BLAKE2b-256 checksum How to use checksums |
d4c49b0fa82c52c796954de52492e3cf9c1f46b3f176db477520b325201c8042
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.7
|
Security for jsdoc 1.0.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.