@git.zone/tsdoc 1.4.5 → 1.5.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.
Files changed (41) hide show
  1. package/dist_ts/00_commitinfo_data.js +3 -3
  2. package/dist_ts/aidocs_classes/commit.js +16 -10
  3. package/dist_ts/aidocs_classes/description.js +14 -6
  4. package/dist_ts/aidocs_classes/projectcontext.d.ts +22 -0
  5. package/dist_ts/aidocs_classes/projectcontext.js +41 -1
  6. package/dist_ts/aidocs_classes/readme.js +10 -4
  7. package/dist_ts/classes.aidoc.d.ts +23 -0
  8. package/dist_ts/classes.aidoc.js +34 -1
  9. package/dist_ts/cli.js +110 -1
  10. package/dist_ts/context/config-manager.d.ts +58 -0
  11. package/dist_ts/context/config-manager.js +183 -0
  12. package/dist_ts/context/context-trimmer.d.ts +52 -0
  13. package/dist_ts/context/context-trimmer.js +199 -0
  14. package/dist_ts/context/enhanced-context.d.ts +75 -0
  15. package/dist_ts/context/enhanced-context.js +272 -0
  16. package/dist_ts/context/index.d.ts +7 -0
  17. package/dist_ts/context/index.js +8 -0
  18. package/dist_ts/context/task-context-factory.d.ts +46 -0
  19. package/dist_ts/context/task-context-factory.js +109 -0
  20. package/dist_ts/context/types.d.ts +89 -0
  21. package/dist_ts/context/types.js +2 -0
  22. package/dist_ts/plugins.d.ts +2 -1
  23. package/dist_ts/plugins.js +3 -2
  24. package/npmextra.json +10 -9
  25. package/package.json +25 -23
  26. package/readme.md +588 -174
  27. package/readme.plan.md +314 -0
  28. package/ts/00_commitinfo_data.ts +2 -2
  29. package/ts/aidocs_classes/commit.ts +21 -9
  30. package/ts/aidocs_classes/description.ts +16 -5
  31. package/ts/aidocs_classes/projectcontext.ts +43 -0
  32. package/ts/aidocs_classes/readme.ts +11 -3
  33. package/ts/classes.aidoc.ts +37 -0
  34. package/ts/cli.ts +128 -0
  35. package/ts/context/config-manager.ts +209 -0
  36. package/ts/context/context-trimmer.ts +246 -0
  37. package/ts/context/enhanced-context.ts +343 -0
  38. package/ts/context/index.ts +32 -0
  39. package/ts/context/task-context-factory.ts +138 -0
  40. package/ts/context/types.ts +95 -0
  41. package/ts/plugins.ts +2 -1
package/readme.md CHANGED
@@ -1,316 +1,730 @@
1
- # @git.zone/tsdoc
2
-
1
+ # @git.zone/tsdoc
3
2
  An advanced TypeScript documentation tool using AI to generate and enhance documentation for TypeScript projects.
4
3
 
5
4
  ## Install
6
5
 
7
- To install `@git.zone/tsdoc`, you can either install it globally or use it with `npx`.
6
+ To install @git.zone/tsdoc, you have two options. You can install it globally so that the CLI commands are available throughout your system, or you can use it with npx if you prefer to keep the installation local to your project.
8
7
 
9
8
  ### Global Installation
10
9
 
11
- You can install `@git.zone/tsdoc` globally on your system using npm:
10
+ To install the tool globally, run the following command in your terminal:
12
11
 
13
12
  ```bash
14
13
  npm install -g @git.zone/tsdoc
15
14
  ```
16
15
 
16
+ Installing globally ensures that the CLI commands (such as tsdoc, tsdoc typedoc, tsdoc aidoc, etc.) are available anywhere on your machine without the need to refer to the local node_modules folder.
17
+
17
18
  ### Usage with npx
18
19
 
19
- If you prefer not to install it globally, you can use it with `npx`:
20
+ If you prefer not to install the tool globally, you can invoke it using npx directly from your project. This method works well if you intend to use the tool on a per-project basis:
20
21
 
21
22
  ```bash
22
23
  npx @git.zone/tsdoc <command>
23
24
  ```
24
25
 
26
+ In the commands below, you will see how to use the various functionalities that @git.zone/tsdoc provides for generating intricate and enhanced documentation for your TypeScript projects.
27
+
25
28
  ## Usage
26
29
 
27
- `@git.zone/tsdoc` provides a comprehensive CLI tool and advanced AI-enhanced features to generate and enhance documentation for your TypeScript projects.
30
+ The @git.zone/tsdoc module provides a very rich and interactive CLI interface together with a set of programmable classes that let you integrate documentation generation into your build processes or workflows. This section will walk you through every aspect of the module—from its basic CLI commands to its advanced internal API usage. All examples provided below use ESM syntax with TypeScript and are designed to be comprehensive. Every code snippet is written so you can easily copy, paste, and adapt to your project. The following guide is divided into several sections covering every major feature, tool integration, and customization options available in the module.
31
+
32
+ -------------------------------------------------------------------
33
+ ### Overview and Core Concepts
34
+
35
+ At its heart, @git.zone/tsdoc is a CLI tool that blends classic documentation generation (using libraries such as TypeDoc) with AI-enhanced techniques. The tool reads your project files, uses a context builder to optimize file content based on token usage and configurable trimming strategies, and then leverages an AI engine to generate enhanced documentation. This complete solution is designed to integrate smoothly into your project pipeline.
28
36
 
29
- ### Using the CLI
37
+ Key features include:
38
+ - **Auto-detection of documentation format**: The CLI attempts to determine the best documentation strategy for your project.
39
+ - **Support for TypeDoc generation**: Build TypeDoc-compatible documentation directly.
40
+ - **AI-Enhanced Documentation (AiDoc)**: Generate a README and project description using artificial intelligence that analyzes your project’s code and context.
41
+ - **Plugin Integration**: The module leverages a variety of plugins (smartfile, smartgit, smartcli, smartai, etc.) to streamline tasks such as file manipulation, CLI interaction, shell command execution, and logging.
42
+ - **Context Trimming and Optimization**: To manage token usage (especially for AI input), the module includes advanced context-building strategies that trim and summarize code files intelligently.
43
+ - **Robust Internal API**: While the primary user interface is through the CLI, the underlying classes (AiDoc, TypeDoc, Readme, etc.) can be used to build custom integrations or extend the tool’s functionality.
30
44
 
31
- The primary interface for `@git.zone/tsdoc` is through its command-line tool. Below, we'll explore the different commands available and provide examples of how to use them.
45
+ Below, you will find detailed explanations along with ESM/TypeScript code examples for all core use cases.
32
46
 
33
- ### Commands
47
+ -------------------------------------------------------------------
48
+ ### Command-Line Interface (CLI) Usage
34
49
 
35
- #### `tsdoc` - Auto-detect Documentation Format
50
+ The most common way to interact with @git.zone/tsdoc is via its command-line interface (CLI). The CLI is designed to auto-detect your project’s context and trigger the appropriate commands based on your needs. Below is a guide on how to use the CLI commands.
36
51
 
37
- The standard command will automatically detect the documentation format of your project and generate the appropriate documentation.
52
+ #### Basic Invocation
53
+
54
+ When you run the command without any arguments, the tool attempts to determine the appropriate documentation generation mode:
38
55
 
39
56
  ```bash
40
57
  tsdoc
41
58
  ```
42
59
 
43
- ### Example
60
+ This will scan the project directory and attempt to detect whether your project follows a TypeDoc convention or if it would benefit from an AI-enhanced documentation build. The auto-detection logic uses the project context (for example, the presence of a ts directory or specific configuration files) to decide the best course of action.
44
61
 
45
- ```typescript
46
- // In a TypeScript project, run the above command.
62
+ ##### Example Scenario
63
+
64
+ Imagine you have a TypeScript project with the following structure:
65
+
66
+ ├── package.json
67
+ ├── ts/
68
+ │   └── index.ts
69
+ └── readme.hints.md
70
+
71
+ When you execute:
72
+
73
+ ```bash
74
+ tsdoc
47
75
  ```
48
76
 
49
- #### `tsdoc typedoc` - Generate Documentation using TypeDoc
77
+ The tool will analyze the project directory, recognizing the ts/ folder, and it will route the command to the appropriate documentation generator, such as the TypeDoc generator if it detects valid structure.
50
78
 
51
- The `typedoc` command will generate documentation compliant with the TypeDoc format.
79
+ #### TypeDoc Command
80
+
81
+ For projects that require a traditional documentation format, you can explicitly generate documentation using the TypeDoc integration:
52
82
 
53
83
  ```bash
54
84
  tsdoc typedoc --publicSubdir docs
55
85
  ```
56
86
 
57
- ### Example
87
+ This command instructs the module to generate HTML documentation using TypeDoc, placing the output into a public directory (or a custom subdirectory as specified).
88
+
89
+ **Inside a TypeScript file, this command can be mirrored by calling the TypeDoc class directly:**
58
90
 
59
91
  ```typescript
60
- import * as plugins from '@push.rocks/smartfile';
92
+ import { TypeDoc } from '@git.zone/tsdoc';
93
+ import * as path from 'path';
94
+
95
+ const cwd = process.cwd();
96
+ const typeDocInstance = new TypeDoc(cwd);
61
97
 
62
- const tsconfigPath = plugins.path.join(__dirname, 'tsconfig.json');
63
- const outputPath = plugins.path.join(__dirname, 'docs');
98
+ const compileDocumentation = async (): Promise<void> => {
99
+ try {
100
+ // Specify the output subdirectory for documentation
101
+ await typeDocInstance.compile({
102
+ publicSubdir: 'docs'
103
+ });
104
+ console.log('Documentation successfully generated using TypeDoc.');
105
+ } catch (error) {
106
+ console.error('Error generating documentation with TypeDoc:', error);
107
+ }
108
+ };
64
109
 
65
- await plugins.smartshellInstance.exec(
66
- `typedoc --tsconfig ${tsconfigPath} --out ${outputPath} index.ts`,
67
- );
110
+ compileDocumentation();
68
111
  ```
69
112
 
70
- #### `tsdoc aidoc` - Generate AI-Enhanced Documentation
113
+ In this example, the script creates an instance of the TypeDoc class passing the current working directory. The compile method is then called with an options object, indicating that the public subdirectory should be named “docs.” The method spawns a shell command using the smart shell plugin to execute the TypeDoc binary.
114
+
115
+ #### AI-Enhanced Documentation Command
71
116
 
72
- The `aidoc` command will use AI to generate an enhanced README and update your project description.
117
+ One of the standout features of this module is its AI-enhanced documentation capabilities. The `aidoc` command integrates with an OpenAI interface to produce a more contextual and detailed README and project description. This is particularly useful when your project codebase has evolved and requires documentation updates based on the current source code.
118
+
119
+ To run the AI-enhanced documentation generation:
73
120
 
74
121
  ```bash
75
122
  tsdoc aidoc
76
123
  ```
77
124
 
78
- ### Example
125
+ In an ESM/TypeScript project, you can use the AiDoc class to programmatically run the same functionality:
79
126
 
80
127
  ```typescript
81
128
  import { AiDoc } from '@git.zone/tsdoc';
82
129
 
83
- (async () => {
84
- const aidoc = new AiDoc();
85
- await aidoc.start();
86
- await aidoc.buildReadme('./');
87
- await aidoc.buildDescription('./');
88
- })();
130
+ const buildEnhancedDocs = async (): Promise<void> => {
131
+ const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
132
+ try {
133
+ // Start the AI interface; this internally checks if the token is valid and persists it
134
+ await aiDoc.start();
135
+
136
+ // Build the README file for the project directory
137
+ console.log('Generating README file using AI...');
138
+ await aiDoc.buildReadme(process.cwd());
139
+
140
+ // Build a new project description based on the codebase
141
+ console.log('Generating updated project description...');
142
+ await aiDoc.buildDescription(process.cwd());
143
+
144
+ console.log('AI-enhanced documentation generated successfully.');
145
+ } catch (error) {
146
+ console.error('Failed to generate AI-enhanced documentation:', error);
147
+ }
148
+ };
149
+
150
+ buildEnhancedDocs();
89
151
  ```
90
152
 
91
- #### `tsdoc test` - Test Your Documentation Setup
153
+ In the above snippet, we import the AiDoc class and create an instance with an OpenAI token. The methods start(), buildReadme(), and buildDescription() streamline the process of generating enhanced documentation by leveraging the underlying AI engine. This code example should serve as a blueprint for those wishing to integrate AI-driven documentation updates as part of their CI/CD pipelines.
154
+
155
+ #### Testing Your Documentation Setup
92
156
 
93
- The `test` command will test your current documentation setup, ensuring everything is configured correctly.
157
+ Before you commit changes to your project documentation, it is often worthwhile to run tests to ensure that your documentation generation process is behaving as expected. The module includes a `test` command:
94
158
 
95
159
  ```bash
96
160
  tsdoc test
97
161
  ```
98
162
 
99
- ### Example
163
+ This command verifies that all components (CLI commands, TypeDoc compilation, AI integration, etc.) are properly configured.
164
+
165
+ Here is an example test script written in TypeScript using a test bundle:
100
166
 
101
167
  ```typescript
102
- import * as plugins from '@git.zone/tsdoc';
168
+ import { expect, tap } from '@push.rocks/tapbundle';
169
+ import { AiDoc } from '@git.zone/tsdoc';
103
170
 
104
- await plugins.runCli().catch((err) => {
105
- console.error(err);
106
- process.exit(1);
171
+ tap.test('AiDoc instance creation', async () => {
172
+ const aidoc = new AiDoc({ OPENAI_TOKEN: 'dummy-token' });
173
+ expect(aidoc).toBeInstanceOf(AiDoc);
107
174
  });
108
- ```
109
175
 
110
- ## Features in Depth
176
+ tap.test('Running AI documentation generation', async () => {
177
+ const aidoc = new AiDoc({ OPENAI_TOKEN: 'dummy-token' });
178
+ await aidoc.start();
179
+
180
+ // Attempt buildReadme and buildDescription synchronously for test coverage
181
+ await aidoc.buildReadme(process.cwd());
182
+ await aidoc.buildDescription(process.cwd());
183
+
184
+ // If no errors are thrown, we assume the process works as expected
185
+ expect(true).toBe(true);
186
+ });
187
+
188
+ tap.start();
189
+ ```
111
190
 
112
- ### Using Plugins
191
+ This test script demonstrates how to automate the validation process by using the provided AiDoc class. Using a testing framework like tap ensures that your documentation generation remains robust even as new features are added or as the project evolves.
113
192
 
114
- `@git.zone/tsdoc` extensively uses plugins to extend its capabilities.
193
+ -------------------------------------------------------------------
194
+ ### Advanced Usage Scenarios
115
195
 
116
- ### Available Plugins
196
+ Beyond using the CLI, @git.zone/tsdoc provides various classes and plugins that allow you to deeply integrate documentation generation within your project. The following sections document advanced usage scenarios where you programmatically interact with different components.
117
197
 
118
- - **npmextra**: Manage npm project-related configurations.
119
- - **qenv**: Environment variable management.
120
- - **smartai**: AI integration.
121
- - **smartcli**: CLI helper.
122
- - **smartdelay**: Simple delay utility.
123
- - **smartfile**: File system utilities.
124
- - **smartinteract**: Interaction helper.
125
- - **smartlog**: Logging utility.
126
- - **smartlogDestinationLocal**: Local file destination for logging.
127
- - **smartpath**: Path utilities.
128
- - **smartshell**: Shell command execution.
129
- - **typedoc**: Documentation generation.
198
+ #### 1. Deep Dive into AiDoc Functionality
130
199
 
131
- ### Example Usage of Plugins
200
+ The AiDoc class is the core of the AI-enhanced documentation generation. It manages interactions with the OpenAI API, handles token validations, and integrates with project-specific configurations.
132
201
 
133
- #### Path Management
202
+ Consider the following advanced usage example:
134
203
 
135
204
  ```typescript
205
+ import { AiDoc } from '@git.zone/tsdoc';
136
206
  import * as path from 'path';
137
207
 
138
- const packageDir = path.join(__dirname, '../');
139
- const cwd = process.cwd();
140
- const binDir = path.join(packageDir, './node_modules/.bin');
141
- const assetsDir = path.join(packageDir, './assets');
142
- const publicDir = path.join(cwd, './public');
143
- const tsDir = path.join(cwd, './ts');
144
- const tsconfigFile = path.join(assetsDir, './tsconfig.json');
145
- const typedocOptionsFile = path.join(assetsDir, './typedoc.json');
208
+ const generateProjectDocs = async () => {
209
+ // Create an instance of the AiDoc class with a configuration object
210
+ // that includes your OpenAI token. This token will be used to query the AI.
211
+ const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
212
+
213
+ // Initialize the AI documentation system.
214
+ await aiDoc.start();
215
+
216
+ // Build the README file for the current project.
217
+ console.log('Building README for the project...');
218
+ await aiDoc.buildReadme(process.cwd());
219
+
220
+ // Build an updated project description based on the analysis of the source files.
221
+ console.log('Building project description...');
222
+ await aiDoc.buildDescription(process.cwd());
223
+
224
+ // You can also generate a commit message based on code changes by using the next commit object generation.
225
+ try {
226
+ console.log('Generating commit message based on your project changes...');
227
+ const nextCommit = await aiDoc.buildNextCommitObject(process.cwd());
228
+ console.log('Next commit message object:', nextCommit);
229
+ } catch (error) {
230
+ console.error('Error generating commit message:', error);
231
+ }
232
+ };
233
+
234
+ generateProjectDocs();
146
235
  ```
147
236
 
148
- #### Logging
237
+ In this example, the AiDoc class handles multiple tasks:
238
+
239
+ - It starts by validating and printing the sanitized token.
240
+ - It generates and writes the README file based on dynamic analysis.
241
+ - It updates the project description stored in your configuration files.
242
+ - It even integrates with Git to produce a suggested commit message that factors in the current state of the project directory.
243
+
244
+ Internally, methods such as buildReadme() interact with the ProjectContext class to gather files and determine the relevant context. This context is trimmed and processed based on token budgets, thus ensuring that the AI interface only receives the information it can effectively process.
245
+
246
+ #### 2. Interacting with the TypeDoc Class Programmatically
247
+
248
+ The TypeDoc class does not merely wrap the standard TypeDoc tool. It adds a layer of automation by preparing the TypeScript environment, generating a temporary tsconfig file, and invoking TypeDoc with the proper configuration. You can use this functionality to conditionally generate documentation or integrate it into your build steps.
249
+
250
+ Below is another example demonstrating the integration:
149
251
 
150
252
  ```typescript
151
- import * as plugins from './plugins';
152
-
153
- const logger = new plugins.smartlog.Smartlog({
154
- logContext: {
155
- company: 'Some Company',
156
- companyunit: 'Some CompanyUnit',
157
- containerName: 'Some Containername',
158
- environment: 'local',
159
- runtime: 'node',
160
- zone: 'gitzone',
161
- },
162
- minimumLogLevel: 'silly',
163
- });
253
+ import { TypeDoc } from '@git.zone/tsdoc';
254
+ import * as path from 'path';
164
255
 
165
- logger.addLogDestination(new plugins.smartlogDestinationLocal.DestinationLocal());
256
+ const generateTypeDocDocs = async () => {
257
+ // Assume you are in the root directory of your TypeScript project
258
+ const cwd = process.cwd();
259
+
260
+ // Create an instance of the TypeDoc class
261
+ const typeDocInstance = new TypeDoc(cwd);
262
+
263
+ // Prepare additional options if necessary (e.g., setting a public subdirectory for docs)
264
+ const options = { publicSubdir: 'documentation' };
265
+
266
+ // Compile your TypeScript project documentation.
267
+ // The compile method handles creating the tsconfig file, running the shell command, and cleaning up afterward.
268
+ try {
269
+ console.log('Compiling TypeScript documentation using TypeDoc...');
270
+ await typeDocInstance.compile(options);
271
+ console.log('Documentation generated at:', path.join(cwd, 'public', 'documentation'));
272
+ } catch (error) {
273
+ console.error('Error compiling TypeDoc documentation:', error);
274
+ }
275
+ };
276
+
277
+ generateTypeDocDocs();
166
278
  ```
167
279
 
168
- ## Advanced Usage
280
+ This script clearly demonstrates how TypeDoc automation is structured inside the module. By invoking the compile() method, the class takes care of setting directory paths, preparing command arguments, and executing the underlying TypeDoc binary using the smart shell plugin.
281
+
282
+ #### 3. Customizing Context Building
169
283
 
170
- ### Using `TypeDoc` Class
284
+ One of the critical functionalities within @git.zone/tsdoc is its ability to build a smart context for documentation generation. The module not only collects file content from your project (like package.json, readme.hints.md, and other source files) but also intelligently trims and summarizes these contents to fit within token limits for AI processing.
171
285
 
172
- The `TypeDoc` class provides utility methods to compile TypeScript documentation.
286
+ Consider the following deep-dive example into the context building process:
173
287
 
174
288
  ```typescript
175
- import { TypeDoc } from '@git.zone/tsdoc/classes.typedoc';
289
+ import { EnhancedContext } from '@git.zone/tsdoc';
290
+ import { ConfigManager } from '@git.zone/tsdoc/dist/ts/context/config-manager.js';
176
291
 
177
- const typeDocInstance = new TypeDoc(paths.cwd);
292
+ const buildProjectContext = async () => {
293
+ const projectDir = process.cwd();
178
294
 
179
- await typeDocInstance.compile({
180
- publicSubdir: 'docs',
181
- });
295
+ // Create an instance of the EnhancedContext class to optimize file content for AI use.
296
+ const enhancedContext = new EnhancedContext(projectDir);
297
+
298
+ // Initialize the context builder. This ensures that configuration (e.g., token budgets, trimming options) is loaded.
299
+ await enhancedContext.initialize();
300
+
301
+ // Optionally, you can choose to set a custom token budget and context mode.
302
+ enhancedContext.setTokenBudget(100000); // for example, limit tokens to 100K
303
+ enhancedContext.setContextMode('trimmed');
304
+
305
+ // Build the context string from selected files in your project.
306
+ const contextResult = await enhancedContext.buildContext('readme');
307
+
308
+ console.log('Context generated with token count:', contextResult.tokenCount);
309
+ console.log('Token savings due to trimming:', contextResult.tokenSavings);
310
+
311
+ // The context string includes file boundaries and token information.
312
+ console.log('Generated Context:', contextResult.context);
313
+ };
314
+
315
+ buildProjectContext();
182
316
  ```
183
317
 
184
- ### Using `AiDoc` Class
318
+ In this example:
319
+ - The EnhancedContext class is initialized with the project directory.
320
+ - Configuration is loaded via the ConfigManager, which reads parameters from npmextra.json.
321
+ - The context builder then gathers files (such as package.json, readme hints, TypeScript sources, etc.), trims unnecessary content, and builds a context string.
322
+ - Finally, it prints the overall token counts and savings, giving you valuable feedback on how the context was optimized for the AI input.
323
+
324
+ This detailed context-building mechanism is essential for managing large TypeScript projects. It ensures that the AI engine can process relevant code data without being overwhelmed by too many tokens.
325
+
326
+ #### 4. Working with the Readme Class for Automatic README Generation
185
327
 
186
- The `AiDoc` class integrates with AI services to enhance your documentation.
328
+ The Readme class in @git.zone/tsdoc takes the AI-enhanced documentation further by not only generating a project-level README but also iterating over submodules within your project. This ensures that every published module has its own complete, AI-generated README.
187
329
 
188
- #### Initializing and Using AI
330
+ Here is an advanced example demonstrating how to trigger README generation for the main project and its submodules:
189
331
 
190
332
  ```typescript
191
333
  import { AiDoc } from '@git.zone/tsdoc';
334
+ import * as path from 'path';
335
+ import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
336
+ import { readFileSync } from 'fs';
337
+
338
+ const buildProjectReadme = async () => {
339
+ const projectDir = process.cwd();
340
+
341
+ // Create an instance of the AiDoc class to handle AI-enhanced docs generation
342
+ const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
343
+
344
+ // Start the AI interface
345
+ await aiDoc.start();
192
346
 
193
- const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
347
+ // Build the primary README for the project directory
348
+ console.log('Generating primary README...');
349
+ await aiDoc.buildReadme(projectDir);
194
350
 
195
- await aiDoc.start();
196
- await aiDoc.buildReadme('./');
197
- await aiDoc.buildDescription('./');
351
+ // Logging function to verify submodule processing
352
+ logger.log('info', `Primary README generated in ${projectDir}`);
353
+
354
+ // Assume that submodules are organized in distinct directories.
355
+ // Here we simulate the process of scanning subdirectories and triggering README generation for each.
356
+ const subModules = ['submodule1', 'submodule2'];
357
+
358
+ // Loop through each submodule directory to generate its README.
359
+ for (const subModule of subModules) {
360
+ const subModuleDir = path.join(projectDir, subModule);
361
+ logger.log('info', `Generating README for submodule: ${subModule}`);
362
+
363
+ // Each submodule README is generated independently.
364
+ await aiDoc.buildReadme(subModuleDir);
365
+
366
+ // Optionally, read the generated README content for verification.
367
+ const readmePath = path.join(subModuleDir, 'readme.md');
368
+ try {
369
+ const readmeContent = readFileSync(readmePath, 'utf8');
370
+ logger.log('info', `Generated README for ${subModule}:\n${readmeContent.substring(0, 200)}...`);
371
+ } catch (error) {
372
+ logger.log('error', `Failed to read README for ${subModule}: ${error}`);
373
+ }
374
+ }
375
+ };
376
+
377
+ buildProjectReadme();
198
378
  ```
199
379
 
200
- #### Retrieving AI Tokens
380
+ In this example, the script:
381
+ - Starts by building the AI-enhanced README for the entire project.
382
+ - Then iterates over a list of submodule directories and generates READMEs for each.
383
+ - Uses the logging utility to provide immediate feedback on the generation process.
384
+ - Optionally, reads back a snippet of the generated file to verify successful documentation generation.
385
+
386
+ This approach ensures that projects with multiple submodules or packages maintain a consistent and high-quality documentation standard across every component.
387
+
388
+ -------------------------------------------------------------------
389
+ ### Plugin-Based Architecture and Integrations
390
+
391
+ Under the hood, @git.zone/tsdoc leverages a number of smaller, focused plugins that extend its functionality. These plugins facilitate file system operations, shell command execution, environment variable management, and logging. The modular design makes it easy to extend or customize the tool according to your needs.
392
+
393
+ The relevant plugins include:
394
+ - smartai: Provides the API integration with OpenAI.
395
+ - smartcli: Handles CLI input parsing and command setup.
396
+ - smartdelay: Manages asynchronous delays and debouncing.
397
+ - smartfile: Offers an abstraction over file I/O operations.
398
+ - smartgit: Facilitates integration with git repositories (e.g., retrieving diffs, commit status).
399
+ - smartinteract: Eases interaction with the user (prompting for tokens, confirming actions).
400
+ - smartlog and smartlogDestinationLocal: Provide comprehensive logging mechanisms.
401
+ - smartpath, smartshell, and smarttime: Manage file paths, execute shell commands, and process time data respectively.
402
+
403
+ Below is a sample snippet illustrating how you might directly interact with a few of these plugins to, for example, run a custom shell command or log events:
201
404
 
202
405
  ```typescript
203
- import * as plugins from '@git.zone/tsdoc/plugins';
406
+ import * as plugins from '@git.zone/tsdoc/dist/ts/plugins.js';
407
+ import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
408
+
409
+ const runCustomCommand = async () => {
410
+ // Create an instance of the smart shell utility
411
+ const smartshellInstance = new plugins.smartshell.Smartshell({
412
+ executor: 'bash',
413
+ pathDirectories: [plugins.smartpath.join(process.cwd(), 'node_modules/.bin')]
414
+ });
204
415
 
205
- const qenv = new plugins.qenv.Qenv();
206
- const openaiToken = await qenv.getEnvVarOnDemand('OPENAI_TOKEN');
416
+ try {
417
+ // Execute a sample shell command, e.g., listing files in the current directory
418
+ const output = await smartshellInstance.exec('ls -la');
419
+ logger.log('info', `Shell command output:\n${output}`);
420
+ } catch (error) {
421
+ logger.log('error', 'Error executing custom shell command:', error);
422
+ }
423
+ };
424
+
425
+ runCustomCommand();
207
426
  ```
208
427
 
209
- ### Testing
428
+ This example shows how to:
429
+ - Import the necessary plugins.
430
+ - Set up a smartshell instance by specifying the shell executor and the directories where executables are located.
431
+ - Execute a command (in this case, listing directory contents) and log the results using the provided logging plugin.
432
+
433
+ Such examples demonstrate the flexibility provided by the module’s internal API. They also illustrate that even if you choose not to use the CLI, you can still leverage the @git.zone/tsdoc functionality programmatically in a highly integrated fashion.
434
+
435
+ -------------------------------------------------------------------
436
+ ### Handling Git Commit Messages with AI
210
437
 
211
- The provided tests demonstrate how to verify the functionality of the `@git.zone/tsdoc` tool.
438
+ A unique feature of this tool is its capacity to assist with creating smart commit messages based on code changes. The Commit class (found within the aidocs_classes directory) ties together output from smartgit and AiDoc to suggest commit messages that are both descriptive and formatted according to conventional commit guidelines.
212
439
 
213
- #### Example Test Script
440
+ Consider this example where you generate a commit message based on the diff from your git repository:
214
441
 
215
442
  ```typescript
216
- import { expect, tap } from '@push.rocks/tapbundle';
217
- import * as tsdoc from '../ts/index';
443
+ import { AiDoc } from '@git.zone/tsdoc';
218
444
 
219
- tap.test('should create AiDoc instance', async () => {
220
- const aidoc = new tsdoc.AiDoc({ OPENAI_TOKEN: 'dummy-token' });
221
- expect(aidoc).toBeInstanceOf(tsdoc.AiDoc);
222
- });
445
+ const generateCommitMessage = async () => {
446
+ // Create an instance of AiDoc
447
+ const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
448
+
449
+ // Initialize the AI service
450
+ await aiDoc.start();
451
+
452
+ try {
453
+ // Generate and retrieve the next commit object based on the uncommitted changes in the repository.
454
+ const commitObject = await aiDoc.buildNextCommitObject(process.cwd());
455
+ console.log('Recommended commit object:', commitObject);
456
+
457
+ // The commit object is structured with the following fields:
458
+ // - recommendedNextVersionLevel: Indicates whether the commit is a fix, feature, or breaking change.
459
+ // - recommendedNextVersionScope: The scope of changes.
460
+ // - recommendedNextVersionMessage: A short commit message.
461
+ // - recommendedNextVersionDetails: A list of details explaining the changes.
462
+ // - recommendedNextVersion: A computed version string.
463
+ } catch (error) {
464
+ console.error('Error generating commit message:', error);
465
+ }
466
+ };
223
467
 
224
- tap.test('should start AiDoc', async () => {
225
- const aidoc = new tsdoc.AiDoc({ OPENAI_TOKEN: 'dummy-token' });
226
- await aidoc.start();
227
- await aidoc.buildReadme('./');
228
- await aidoc.buildDescription('./');
229
- });
468
+ generateCommitMessage();
469
+ ```
230
470
 
231
- tap.start();
471
+ The process works as follows:
472
+ 1. The AiDoc instance is created and started.
473
+ 2. The tool uses the smartgit plugin to fetch uncommitted changes from the repository.
474
+ 3. It then builds a context string incorporating file diffs and project metadata.
475
+ 4. Finally, the OpenAI API is queried to produce a commit message formatted as JSON. This JSON object is parsed and can be used directly in your git workflow.
476
+
477
+ This advanced integration assists teams in maintaining consistent commit message standards while reducing the manual burden of summarizing code changes.
478
+
479
+ -------------------------------------------------------------------
480
+ ### Detailed Explanation of Internal Mechanics
481
+
482
+ If you are curious about the intricate inner workings of @git.zone/tsdoc and wish to extend or debug its behavior, here is an in-depth explanation of some internal mechanisms.
483
+
484
+ #### Context Trimming Strategy
485
+
486
+ Managing token count is critical when interfacing with APIs that have strict limits. The module uses a multi-step process:
487
+ - It gathers various files (such as package.json, ts files, readme hints).
488
+ - It sorts the files and calculates the token count using the GPT tokenizer.
489
+ - It applies trimming strategies such as removing function implementations or comments in TypeScript files, based on a configurable set of parameters.
490
+ - Finally, it constructs a unified context string that includes file boundaries for clarity.
491
+
492
+ For example, the ContextTrimmer class carries out these transformations:
493
+
494
+ ```typescript
495
+ import { ContextTrimmer } from '@git.zone/tsdoc/dist/ts/context/context-trimmer.js';
496
+
497
+ const trimFileContent = (filePath: string, content: string): string => {
498
+ // Create an instance of ContextTrimmer with default configuration
499
+ const trimmer = new ContextTrimmer({
500
+ removeImplementations: true,
501
+ preserveJSDoc: true,
502
+ maxFunctionLines: 5,
503
+ removeComments: true,
504
+ removeBlankLines: true
505
+ });
506
+
507
+ // Trim the content based on the file type and configured options
508
+ const trimmedContent = trimmer.trimFile(filePath, content, 'trimmed');
509
+ return trimmedContent;
510
+ };
511
+
512
+ // Example usage with a TypeScript file
513
+ const tsFileContent = `
514
+ /**
515
+ * This function calculates the sum of two numbers.
516
+ */
517
+ export const add = (a: number, b: number): number => {
518
+ // Calculation logic
519
+ return a + b;
520
+ };
521
+ `;
522
+
523
+ const trimmedTSContent = trimFileContent('src/math.ts', tsFileContent);
524
+ console.log('Trimmed TypeScript File Content:\n', trimmedTSContent);
232
525
  ```
233
526
 
234
- ### Internals
527
+ This process helps in reducing the number of tokens before sending the data to the AI API while preserving the essential context needed for documentation generation.
235
528
 
236
- The `@git.zone/tsdoc` consists of several internal classes and utilities that streamline its functionality.
529
+ #### Dynamic Configuration Management
237
530
 
238
- #### File Paths Management
531
+ The module’s configuration is stored in the npmextra.json file and includes settings for context building, trimming strategies, and task-specific options. The ConfigManager class reads these settings and merges them with default values. This dynamic configuration system ensures that the behavior of the documentation tool can be easily adjusted without altering the source code.
239
532
 
240
- Located in `ts/paths.ts`, the file defines various directories and file paths used by the tool.
533
+ ```typescript
534
+ import { ConfigManager } from '@git.zone/tsdoc/dist/ts/context/config-manager.js';
535
+
536
+ const updateDocumentationConfig = async () => {
537
+ const projectDir = process.cwd();
538
+ const configManager = ConfigManager.getInstance();
539
+
540
+ // Initialize the configuration manager with the project directory
541
+ await configManager.initialize(projectDir);
542
+
543
+ // Retrieve the current configuration
544
+ let currentConfig = configManager.getConfig();
545
+ console.log('Current context configuration:', currentConfig);
546
+
547
+ // If you want to change some parameters (e.g., maxTokens), update and then save the new configuration
548
+ const newConfig = { maxTokens: 150000 };
549
+ await configManager.updateConfig(newConfig);
550
+
551
+ console.log('Configuration updated successfully.');
552
+ };
553
+
554
+ updateDocumentationConfig();
555
+ ```
556
+
557
+ In this snippet, the ConfigManager:
558
+ - Loads current configuration from npmextra.json.
559
+ - Allows updates to specific keys (such as token limits).
560
+ - Persists these changes back to the file system using the smartfile plugin.
561
+
562
+ #### Logging and Diagnostic Output
563
+
564
+ Throughout its execution, @git.zone/tsdoc logs important information such as token counts, file statistics, and shell command outputs. This logging is accomplished through a combination of the smartlog and smartlogDestinationLocal plugins. The following example illustrates how logging can help diagnose execution issues:
241
565
 
242
566
  ```typescript
243
- import * as plugins from './plugins';
244
-
245
- export const packageDir = plugins.path.join(
246
- plugins.smartpath.get.dirnameFromImportMetaUrl(import.meta.url),
247
- '../',
248
- );
249
- export const cwd = process.cwd();
250
- export const binDir = plugins.path.join(packageDir, './node_modules/.bin');
251
- export const assetsDir = plugins.path.join(packageDir, './assets');
252
- export const publicDir = plugins.path.join(cwd, './public');
253
- export const tsDir = plugins.path.join(cwd, './ts');
254
- export const tsconfigFile = plugins.path.join(assetsDir, './tsconfig.json');
255
- export const typedocOptionsFile = plugins.path.join(assetsDir, './typedoc.json');
567
+ import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
568
+
569
+ const logDiagnosticInfo = () => {
570
+ logger.log('info', 'Starting documentation generation process...');
571
+
572
+ // Log additional contextual information
573
+ logger.log('debug', 'Project directory:', process.cwd());
574
+ logger.log('debug', 'Token budget set for context building:', 150000);
575
+
576
+ // Simulate a long-running process
577
+ setTimeout(() => {
578
+ logger.log('info', 'Documentation generation process completed successfully.');
579
+ }, 2000);
580
+ };
581
+
582
+ logDiagnosticInfo();
256
583
  ```
257
584
 
258
- #### Utility Commands
585
+ Using comprehensive logging, the tool provides feedback not only during normal execution but also in error scenarios, allowing developers to troubleshoot and optimize their documentation generation workflow.
259
586
 
260
- Define utility commands that streamline various processes.
587
+ -------------------------------------------------------------------
588
+ ### Integrating @git.zone/tsdoc into a Continuous Integration Pipeline
261
589
 
262
- ##### Example: SmartCLI Usage
590
+ For teams looking to integrate documentation generation into their CI processes, @git.zone/tsdoc can be harnessed by scripting the CLI commands or by embedding the class-based API directly into your build scripts. Here’s an example of a CI script written in TypeScript that runs as part of a GitHub Action or similar workflow:
263
591
 
264
592
  ```typescript
265
- // Import required modules and plugins
266
- import * as plugins from './plugins';
267
- import * as paths from './paths';
268
-
269
- // TypeDoc and AiDoc classes
270
- import { TypeDoc } from './classes.typedoc';
271
- import { AiDoc } from './classes.aidoc';
272
-
273
- // Export a run function
274
- export const run = async () => {
275
- const tsdocCli = new plugins.smartcli.Smartcli();
276
-
277
- tsdocCli.standardCommand().subscribe(async (argvArg) => {
278
- switch (true) {
279
- case await TypeDoc.isTypeDocDir(paths.cwd):
280
- tsdocCli.triggerCommand('typedoc', argvArg);
281
- break;
282
- default:
283
- console.error(`Cannot determine docs format at ${paths.cwd}`);
284
- }
285
- });
593
+ import { runCli } from '@git.zone/tsdoc';
594
+ import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
595
+
596
+ const runDocumentationPipeline = async () => {
597
+ try {
598
+ logger.log('info', 'Starting the documentation pipeline...');
599
+
600
+ // Run the CLI which automatically detects the project context and generates docs.
601
+ await runCli();
602
+
603
+ logger.log('info', 'Documentation pipeline completed successfully.');
604
+ } catch (error) {
605
+ logger.log('error', 'Documentation pipeline encountered an error:', error);
606
+ process.exit(1);
607
+ }
608
+ };
286
609
 
287
- tsdocCli.addCommand('typedoc').subscribe(async (argvArg) => {
288
- const typeDocInstance = new TypeDoc(paths.cwd);
289
- await typeDocInstance.compile({
290
- publicSubdir: argvArg.publicSubdir,
291
- });
292
- });
610
+ runDocumentationPipeline();
611
+ ```
293
612
 
294
- tsdocCli.addCommand('aidoc').subscribe(async (argvArg) => {
295
- const aidocInstance = new AiDoc(argvArg);
296
- await aidocInstance.start();
297
- await aidocInstance.buildReadme(paths.cwd);
298
- await aidocInstance.buildDescription(paths.cwd);
299
- });
613
+ In a CI environment, you can invoke this script to ensure that documentation is generated or updated as part of your deployment process. The process includes building the README, updating project descriptions, and generating TypeDoc documentation if the project structure warrants it.
614
+
615
+ -------------------------------------------------------------------
616
+ ### Comprehensive Workflow Example
300
617
 
301
- tsdocCli.startParse();
618
+ Below is a full-fledged example that combines many of the above functionalities into a single workflow. This script is intended to be run as part of your build process or as a standalone command, and it demonstrates how to initialize all parts of the module, generate documentation for the main project and its submodules, update configuration, and log key diagnostics.
619
+
620
+ ```typescript
621
+ import { AiDoc } from '@git.zone/tsdoc';
622
+ import { TypeDoc } from '@git.zone/tsdoc';
623
+ import { ConfigManager } from '@git.zone/tsdoc/dist/ts/context/config-manager.js';
624
+ import { EnhancedContext } from '@git.zone/tsdoc/dist/ts/context/enhanced-context.js';
625
+ import * as path from 'path';
626
+ import { logger } from '@git.zone/tsdoc/dist/ts/logging.js';
627
+
628
+ const runFullDocumentationWorkflow = async () => {
629
+ const projectDir = process.cwd();
630
+
631
+ // Initialize configuration management
632
+ const configManager = ConfigManager.getInstance();
633
+ await configManager.initialize(projectDir);
634
+ logger.log('info', `Loaded configuration for project at ${projectDir}`);
635
+
636
+ // Step 1: Generate conventional TypeDoc documentation
637
+ const typeDocInstance = new TypeDoc(projectDir);
638
+ try {
639
+ logger.log('info', 'Starting TypeDoc documentation generation...');
640
+ await typeDocInstance.compile({ publicSubdir: 'docs' });
641
+ logger.log('info', `TypeDoc documentation generated in ${path.join(projectDir, 'public', 'docs')}`);
642
+ } catch (error) {
643
+ logger.log('error', 'Error during TypeDoc generation:', error);
644
+ }
645
+
646
+ // Step 2: Run AI-enhanced documentation generation
647
+ const aiDoc = new AiDoc({ OPENAI_TOKEN: 'your-openai-token' });
648
+ await aiDoc.start();
649
+
650
+ // Generate main README and updated project description
651
+ try {
652
+ logger.log('info', 'Generating main README via AI-enhanced documentation...');
653
+ await aiDoc.buildReadme(projectDir);
654
+ logger.log('info', 'Main README generated successfully.');
655
+
656
+ logger.log('info', 'Generating updated project description...');
657
+ await aiDoc.buildDescription(projectDir);
658
+ logger.log('info', 'Project description updated successfully.');
659
+ } catch (error) {
660
+ logger.log('error', 'Error generating AI-enhanced documentation:', error);
661
+ }
662
+
663
+ // Step 3: Generate contextual data using EnhancedContext
664
+ const enhancedContext = new EnhancedContext(projectDir);
665
+ await enhancedContext.initialize();
666
+ enhancedContext.setContextMode('trimmed');
667
+ enhancedContext.setTokenBudget(150000);
668
+
669
+ const contextResult = await enhancedContext.buildContext('readme');
670
+ logger.log('info', `Context built successfully. Total tokens: ${contextResult.tokenCount}. Savings: ${contextResult.tokenSavings}`);
671
+
672
+ // Step 4: Process submodules (if any) and generate READMEs
673
+ const subModules = ['submodule1', 'submodule2'];
674
+ for (const subModule of subModules) {
675
+ const subModuleDir = path.join(projectDir, subModule);
676
+ logger.log('info', `Processing submodule: ${subModule}`);
677
+ try {
678
+ await aiDoc.buildReadme(subModuleDir);
679
+ logger.log('info', `Submodule README generated for ${subModule}`);
680
+ } catch (error) {
681
+ logger.log('error', `Failed to generate README for ${subModule}:`, error);
682
+ }
683
+ }
684
+
685
+ // Optional: Generate a commit message suggestion based on current changes
686
+ try {
687
+ logger.log('info', 'Generating commit message suggestion...');
688
+ const commitObject = await aiDoc.buildNextCommitObject(projectDir);
689
+ logger.log('info', 'Suggested commit message object:', commitObject);
690
+ } catch (error) {
691
+ logger.log('error', 'Error generating commit message suggestion:', error);
692
+ }
693
+
694
+ logger.log('info', 'Full documentation workflow completed successfully.');
302
695
  };
696
+
697
+ runFullDocumentationWorkflow();
303
698
  ```
304
699
 
305
- By leveraging these functionalities, you can configure and extend `@git.zone/tsdoc` to fit your specific documentation generation needs.
700
+ This comprehensive workflow showcases the integration of various facets of the @git.zone/tsdoc module:
701
+ - Loading and updating configuration via the ConfigManager.
702
+ - Generating static documentation using TypeDoc.
703
+ - Enhancing documentation with AI through the AiDoc class.
704
+ - Optimizing project context with the EnhancedContext class.
705
+ - Iterating over submodules to ensure all parts of your project are documented.
706
+ - Providing useful diagnostic logging for every step.
707
+
708
+ -------------------------------------------------------------------
709
+ ### Wrapping Up the Usage Guide
710
+
711
+ The examples provided above demonstrate that @git.zone/tsdoc is not simply a CLI tool—it is a complete documentation framework designed to adapt to your workflow. Whether you are a developer looking to automate documentation updates in your CI pipeline or a team seeking an AI-powered enhancement for your project metadata, this module offers a wide range of interfaces and hooks for you to leverage.
712
+
713
+ Key takeaways:
714
+ - The CLI handles most routine tasks automatically while also exposing commands for specific documentation generation strategies.
715
+ - Programmatic usage allows deep integration with your project’s build and commit processes.
716
+ - The internal architecture—built on plugins, context optimization, and extensive logging—ensures that the tool can scale with project complexity.
717
+ - Advanced users can customize context trimming, file inclusion rules, and even modify AI queries to better suit their project’s needs.
718
+
719
+ Each code example provided here is written using modern ESM syntax and TypeScript to ensure compatibility with current development practices. Since the module is designed with extensibility in mind, developers are encouraged to explore the source code (especially the classes in the ts/ and ts/aidocs_classes directories) for further customization opportunities.
306
720
 
307
- ### Further Enhancements
721
+ By integrating @git.zone/tsdoc into your workflow, you ensure that your project documentation remains accurate, comprehensive, and reflective of your latest code changes—whether you are generating a simple README or a complex API documentation set enhanced by AI insights.
308
722
 
309
- The `@git.zone/tsdoc` tool is designed to be extensible. Explore the source files and plugins to add more functionality or integrate with other tools as needed. This README provides an extensive overview of the commands and features but it's always beneficial to dive into the source code to understand the intricacies and potential customizations. Happy documenting!
723
+ Happy documenting!
310
724
 
311
725
  ## License and Legal Information
312
726
 
313
- This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
727
+ This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
314
728
 
315
729
  **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
316
730