jsdoc-builder 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.MD ADDED
@@ -0,0 +1,105 @@
1
+ # JSDoc Builder
2
+
3
+ JSDoc Builder is a CLI tool for automatically generating JSDoc comments for JavaScript and TypeScript files. It parses functions and variables to infer parameter types, return types, and descriptions, and then inserts JSDoc comments directly into the source code.
4
+
5
+ ## Features
6
+
7
+ - Automatically generates JSDoc comments for:
8
+ - Function declarations
9
+ - Arrow functions
10
+ - TypeScript types and interfaces
11
+ - Infers parameter and return types from TypeScript annotations.
12
+ - Outputs clean and structured JSDoc comments.
13
+
14
+ ## Installation
15
+
16
+ Install the library globally or locally via npm:
17
+
18
+ ```bash
19
+ npm install jsdoc-builder -g
20
+ ```
21
+
22
+ or
23
+
24
+ ```bash
25
+ npm install jsdoc-builder --save-dev
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ### CLI Command
31
+
32
+ Run the following command to generate JSDoc comments for a file:
33
+
34
+ ```bash
35
+ jsdoc-builder <file-path>
36
+ ```
37
+
38
+ Replace `<file-path>` with the path to the JavaScript or TypeScript file you want to process.
39
+
40
+ ### Example
41
+
42
+ #### Input File (`example.ts`):
43
+
44
+ ```typescript
45
+ function add(a: number, b: number) {
46
+ return a + b;
47
+ }
48
+
49
+ const multiply = (a: number, b: number): number => {
50
+ return a * b;
51
+ };
52
+ ```
53
+
54
+ #### Command:
55
+
56
+ ```bash
57
+ jsdoc-builder example.ts
58
+ ```
59
+
60
+ #### Output File (`example.ts`):
61
+
62
+ ```typescript
63
+ /**
64
+ * @description Function add
65
+ * @param {number} a
66
+ * @param {number} b
67
+ * @returns {void}
68
+ */
69
+ function add(a: number, b: number) {
70
+ return a + b;
71
+ }
72
+
73
+ /**
74
+ * @description Function multiply
75
+ * @param {number} a
76
+ * @param {number} b
77
+ * @returns {number}
78
+ */
79
+ const multiply = (a: number, b: number): number => {
80
+ return a * b;
81
+ };
82
+ ```
83
+
84
+ ## API
85
+
86
+ ### `generateJSDoc(filePath: string): void`
87
+
88
+ - **Description**: Processes the specified file to add JSDoc comments.
89
+ - **Parameters**:
90
+ - `filePath` (string): The path to the file to be processed.
91
+ - **Returns**: `void`
92
+
93
+ ## Contributing
94
+
95
+ Contributions are welcome! Please follow these steps:
96
+
97
+ 1. Fork the repository.
98
+ 2. Create a new branch: `git checkout -b feature-name`.
99
+ 3. Commit your changes: `git commit -m 'Add feature-name'`.
100
+ 4. Push to the branch: `git push origin feature-name`.
101
+ 5. Submit a pull request.
102
+
103
+ ## License
104
+
105
+ This project is licensed under the MIT License. See the LICENSE file for details.
package/dist/cli.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const commander_1 = require("commander");
5
+ const index_1 = require("./index");
6
+ commander_1.program
7
+ .argument("<file>", "The TypeScript or JavaScript file to process")
8
+ .description("Generate JSDoc comments for the given TypeScript or JavaScript file")
9
+ .action((file) => {
10
+ (0, index_1.generateJSDoc)(file);
11
+ });
12
+ commander_1.program.parse(process.argv);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ const multiply = ({ x, y }) => x * y;
@@ -0,0 +1,37 @@
1
+ import ts from "typescript";
2
+ import fs from "fs";
3
+ export function generateJSDoc(filePath) {
4
+ const fileContent = fs.readFileSync(filePath, "utf-8");
5
+ const sourceFile = ts.createSourceFile(filePath, fileContent, ts.ScriptTarget.Latest);
6
+ const functions = [];
7
+ function visit(node) {
8
+ if (ts.isFunctionDeclaration(node) ||
9
+ ts.isFunctionExpression(node) ||
10
+ ts.isArrowFunction(node)) {
11
+ const functionName = node.name?.text || "Anonymous";
12
+ const params = node.parameters
13
+ .map((param) => {
14
+ const paramName = param.name?.getText(sourceFile) || "unknown";
15
+ const paramType = param.type ? param.type.getText(sourceFile) : "any";
16
+ return `@param {${paramType}} ${paramName}`;
17
+ })
18
+ .join("\n");
19
+ const returnType = node.type
20
+ ? `@returns {${node.type.getText(sourceFile)}}`
21
+ : "@returns {any}";
22
+ const jsDoc = `
23
+ /**
24
+ * @function ${functionName}
25
+ * ${params}
26
+ * ${returnType}
27
+ */
28
+ `;
29
+ functions.push(jsDoc);
30
+ }
31
+ ts.forEachChild(node, visit);
32
+ }
33
+ visit(sourceFile);
34
+ // JSDoc을 원본 파일 상단에 삽입
35
+ const updatedContent = functions.join("\n") + "\n\n" + fileContent;
36
+ fs.writeFileSync(filePath, updatedContent, "utf-8");
37
+ }
package/dist/index.js ADDED
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateJSDoc = void 0;
4
+ const ts = require("typescript");
5
+ const fs = require("fs");
6
+ /**
7
+ * Parses a TypeScript or JavaScript file and adds JSDoc comments to functions.
8
+ * @param filePath - The path of the file to process.
9
+ */
10
+ function generateJSDoc(filePath) {
11
+ const sourceCode = fs.readFileSync(filePath, "utf-8");
12
+ const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true);
13
+ const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
14
+ function visit(node) {
15
+ if (ts.isFunctionDeclaration(node) && node.name) {
16
+ const jsDoc = createJSDoc(node.name.text, node.parameters, node.type);
17
+ ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, jsDoc.comment, true);
18
+ return node;
19
+ }
20
+ // Check for arrow functions assigned to a constant
21
+ if (ts.isVariableDeclaration(node) &&
22
+ node.initializer &&
23
+ ts.isArrowFunction(node.initializer)) {
24
+ const jsDoc = createJSDoc(node.name.getText(), node.initializer.parameters, node.initializer.type);
25
+ // Add JSDoc to the entire variable statement for clarity
26
+ const parent = node.parent;
27
+ if (ts.isVariableDeclarationList(parent) &&
28
+ parent.declarations.length === 1) {
29
+ ts.addSyntheticLeadingComment(parent.parent, ts.SyntaxKind.MultiLineCommentTrivia, jsDoc.comment, true);
30
+ }
31
+ return node;
32
+ }
33
+ return ts.visitEachChild(node, visit, context);
34
+ }
35
+ // Create a transformation context
36
+ const context = {
37
+ factory: ts.factory,
38
+ startLexicalEnvironment: () => { },
39
+ endLexicalEnvironment: () => [],
40
+ suspendLexicalEnvironment: () => { },
41
+ resumeLexicalEnvironment: () => { },
42
+ requestEmitHelper: () => { },
43
+ readEmitHelpers: () => undefined,
44
+ enableSubstitution: () => { },
45
+ isSubstitutionEnabled: () => false,
46
+ onSubstituteNode: (hint, node) => node,
47
+ enableEmitNotification: () => { },
48
+ isEmitNotificationEnabled: () => false,
49
+ onEmitNode: (hint, node, emitCallback) => emitCallback(hint, node),
50
+ getCompilerOptions: () => ({}),
51
+ hoistFunctionDeclaration: () => { },
52
+ hoistVariableDeclaration: () => { },
53
+ };
54
+ const result = ts.transform(sourceFile, [
55
+ (context) => (rootNode) => ts.visitNode(rootNode, visit),
56
+ ]);
57
+ const transformedSourceFile = result.transformed[0];
58
+ const updatedCode = printer.printFile(transformedSourceFile);
59
+ fs.writeFileSync(filePath, updatedCode, "utf-8");
60
+ }
61
+ exports.generateJSDoc = generateJSDoc;
62
+ /**
63
+ * Creates a JSDoc comment.
64
+ * @param functionName - The name of the function.
65
+ * @param parameters - The parameters of the function.
66
+ * @param returnType - The return type of the function.
67
+ * @returns A JSDoc comment as a string.
68
+ */
69
+ function createJSDoc(functionName, parameters, returnType) {
70
+ const paramTags = parameters.map((param) => ({
71
+ tagName: "param",
72
+ name: param.name.getText(),
73
+ type: param.type ? param.type.getText() : "any",
74
+ }));
75
+ const returnTag = {
76
+ tagName: "returns",
77
+ type: returnType ? returnType.getText() : "void",
78
+ };
79
+ const commentText = [
80
+ `* @description Press Your { Function ${functionName} } Description`,
81
+ ...paramTags.map((tag) => `* @param {${tag.type}} ${tag.name}`),
82
+ `* @returns {${returnTag.type}}`,
83
+ ].join("\n");
84
+ return { comment: `*\n${commentText}\n` };
85
+ }
package/dist/parse.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateJSDoc = void 0;
4
+ const fs = require("fs");
5
+ const ts = require("typescript");
6
+ function generateJSDoc(filePath) {
7
+ const fileContent = fs.readFileSync(filePath, "utf-8");
8
+ const sourceFile = ts.createSourceFile(filePath, fileContent, ts.ScriptTarget.Latest, true);
9
+ // Example: Traverse the AST and insert JSDoc
10
+ ts.forEachChild(sourceFile, (node) => {
11
+ if (ts.isFunctionDeclaration(node) && node.name) {
12
+ const functionName = node.name.text;
13
+ console.log(`Found function: ${functionName}`);
14
+ // Add logic to generate JSDoc comments
15
+ }
16
+ });
17
+ // Save the updated file (placeholder)
18
+ console.log(`Generated JSDoc for: ${filePath}`);
19
+ }
20
+ exports.generateJSDoc = generateJSDoc;
package/dist/parser.js ADDED
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseFile = void 0;
4
+ const ts = require("typescript");
5
+ /**
6
+ * Parse a TypeScript or JavaScript file to extract functions
7
+ * @param content File content
8
+ * @returns Array of FunctionInfo
9
+ */
10
+ function parseFile(content) {
11
+ const sourceFile = ts.createSourceFile("temp.ts", content, ts.ScriptTarget.ESNext, true);
12
+ const functions = [];
13
+ function visit(node) {
14
+ if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) {
15
+ const name = node.name ? node.name.text : "anonymous";
16
+ const params = node.parameters.map((param) => ({
17
+ name: param.name.getText(),
18
+ type: param.type ? param.type.getText() : "any",
19
+ description: "",
20
+ }));
21
+ const returns = {
22
+ type: node.type ? node.type.getText() : "void",
23
+ description: "",
24
+ };
25
+ functions.push({
26
+ name,
27
+ description: `Function ${name}`,
28
+ params,
29
+ returns,
30
+ start: node.pos,
31
+ });
32
+ }
33
+ ts.forEachChild(node, visit);
34
+ }
35
+ visit(sourceFile);
36
+ return functions;
37
+ }
38
+ exports.parseFile = parseFile;
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const commander_1 = require("commander");
5
+ const index_1 = require("./index");
6
+ commander_1.program
7
+ .command("generate <file>")
8
+ .description("Generate JSDoc comments for the given TypeScript or JavaScript file")
9
+ .action((file) => {
10
+ (0, index_1.generateJSDoc)(file);
11
+ });
12
+ commander_1.program.parse(process.argv);
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.generateJSDoc = void 0;
27
+ const fs = __importStar(require("fs"));
28
+ const parser_1 = require("./parser");
29
+ const utils_1 = require("./utils");
30
+ const utils_2 = require("./utils");
31
+ /**
32
+ * Main function to generate JSDoc for a file
33
+ * @param filePath Path to the file
34
+ */
35
+ function generateJSDoc(filePath) {
36
+ if (!(0, utils_1.fileExists)(filePath)) {
37
+ console.error(`File not found: ${filePath}`);
38
+ return;
39
+ }
40
+ const content = fs.readFileSync(filePath, "utf-8");
41
+ const functions = (0, parser_1.parseFile)(content);
42
+ let updatedContent = content;
43
+ functions.forEach((func) => {
44
+ const jsdoc = (0, utils_2.formatJSDoc)(func.description, func.params, func.returns);
45
+ // 삽입할 위치 찾기
46
+ const insertPosition = func.start;
47
+ updatedContent =
48
+ updatedContent.slice(0, insertPosition) +
49
+ jsdoc +
50
+ "\n" +
51
+ updatedContent.slice(insertPosition);
52
+ });
53
+ (0, utils_1.writeFile)(filePath, updatedContent);
54
+ console.log(`JSDoc comments added to ${filePath}`);
55
+ }
56
+ exports.generateJSDoc = generateJSDoc;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.parseFile = void 0;
27
+ const ts = __importStar(require("typescript"));
28
+ /**
29
+ * Parse a TypeScript or JavaScript file to extract functions
30
+ * @param content File content
31
+ * @returns Array of FunctionInfo
32
+ */
33
+ function parseFile(content) {
34
+ const sourceFile = ts.createSourceFile("temp.ts", content, ts.ScriptTarget.ESNext, true);
35
+ const functions = [];
36
+ function visit(node) {
37
+ if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) {
38
+ const name = node.name ? node.name.text : "anonymous";
39
+ const params = node.parameters.map((param) => ({
40
+ name: param.name.getText(),
41
+ type: param.type ? param.type.getText() : "any",
42
+ description: "",
43
+ }));
44
+ const returns = {
45
+ type: node.type ? node.type.getText() : "void",
46
+ description: "",
47
+ };
48
+ functions.push({
49
+ name,
50
+ description: `Function ${name}`,
51
+ params,
52
+ returns,
53
+ start: node.pos,
54
+ });
55
+ }
56
+ ts.forEachChild(node, visit);
57
+ }
58
+ visit(sourceFile);
59
+ return functions;
60
+ }
61
+ exports.parseFile = parseFile;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.formatJSDoc = exports.writeFile = exports.fileExists = void 0;
27
+ const fs = __importStar(require("fs"));
28
+ /**
29
+ * Check if the file exists
30
+ * @param filePath Path to the file
31
+ * @returns True if the file exists
32
+ */
33
+ function fileExists(filePath) {
34
+ return fs.existsSync(filePath);
35
+ }
36
+ exports.fileExists = fileExists;
37
+ /**
38
+ * Write content to a file
39
+ * @param filePath Path to the file
40
+ * @param content Content to write
41
+ */
42
+ function writeFile(filePath, content) {
43
+ fs.writeFileSync(filePath, content, "utf-8");
44
+ }
45
+ exports.writeFile = writeFile;
46
+ /**
47
+ * Format a JSDoc comment
48
+ * @param description Description of the function
49
+ * @param params Parameters of the function
50
+ * @param returns Return type of the function
51
+ * @returns Formatted JSDoc string
52
+ */
53
+ function formatJSDoc(description, params, returns) {
54
+ const paramDocs = params
55
+ .map((param) => ` * @param {${param.type}} ${param.name} - ${param.description}`)
56
+ .join("\n");
57
+ const returnDoc = ` * @returns {${returns.type}} - ${returns.description}`;
58
+ return `/**
59
+ * ${description}
60
+ ${paramDocs}
61
+ ${returnDoc}
62
+ */`;
63
+ }
64
+ exports.formatJSDoc = formatJSDoc;
package/dist/utils.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatJSDoc = exports.writeFile = exports.fileExists = void 0;
4
+ const fs = require("fs");
5
+ /**
6
+ * Check if the file exists
7
+ * @param filePath Path to the file
8
+ * @returns True if the file exists
9
+ */
10
+ function fileExists(filePath) {
11
+ return fs.existsSync(filePath);
12
+ }
13
+ exports.fileExists = fileExists;
14
+ /**
15
+ * Write content to a file
16
+ * @param filePath Path to the file
17
+ * @param content Content to write
18
+ */
19
+ function writeFile(filePath, content) {
20
+ fs.writeFileSync(filePath, content, "utf-8");
21
+ }
22
+ exports.writeFile = writeFile;
23
+ /**
24
+ * Format a JSDoc comment
25
+ * @param description Description of the function
26
+ * @param params Parameters of the function
27
+ * @param returns Return type of the function
28
+ * @returns Formatted JSDoc string
29
+ */
30
+ function formatJSDoc(description, params, returns) {
31
+ const paramDocs = params
32
+ .map((param) => ` * @param {${param.type}} ${param.name} - ${param.description}`)
33
+ .join("\n");
34
+ const returnDoc = ` * @returns {${returns.type}} - ${returns.description}`;
35
+ return `/**
36
+ * "vv"${description}
37
+ ${paramDocs}
38
+ ${returnDoc}
39
+ */`;
40
+ }
41
+ exports.formatJSDoc = formatJSDoc;
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "jsdoc-builder",
3
+ "version": "0.0.1",
4
+ "author": "dori",
5
+ "description": "Generate JSDoc comments for JavaScript and TypeScript files.",
6
+ "bin": {
7
+ "jsdoc-builder": "./dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "license": "MIT",
13
+ "keywords": [
14
+ "jsdoc-generator",
15
+ "jsdoc",
16
+ "typescript",
17
+ "javascript",
18
+ "documentation",
19
+ "cli",
20
+ "auto-jsdoc"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "start": "node dist/cli.js",
25
+ "test": "ts-node src/cli.ts"
26
+ },
27
+ "dependencies": {
28
+ "commander": "^10.0.0",
29
+ "typescript": "^5.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^20.0.0",
33
+ "ts-node": "^10.0.0"
34
+ }
35
+ }