@sampathkumara/express-to-dart-endpoints-builder 1.0.0

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/CLAUDE.md ADDED
@@ -0,0 +1,304 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ This is a modular npm package that provides an Express.js-to-Dart code generator. It automatically generates production-ready Dart API clients from Express.js route definitions with full JSDoc support, authentication handling, and type mapping.
8
+
9
+ ## Package Structure
10
+
11
+ ```
12
+ express-to-dart-endpoints-builder/
13
+ ├── bin/
14
+ │ └── cli.js # CLI entry point
15
+ ├── src/
16
+ │ ├── index.js # Main export & orchestration
17
+ │ ├── config.js # Configuration loading and validation
18
+ │ ├── parser.js # Route parsing and tree building
19
+ │ ├── generator.js # Dart code generation
20
+ │ ├── typeMapper.js # JS to Dart type mapping
21
+ │ └── utils.js # Utility functions
22
+ ├── package.json # npm package metadata
23
+ ├── README.md # User-facing documentation
24
+ └── CLAUDE.md # This file
25
+ ```
26
+
27
+ ## Quick Start Commands
28
+
29
+ - **Generate Dart API client**: `npm run generate` or `express-to-dart`
30
+ - **Initialize config**: `express-to-dart init`
31
+ - **Show help**: `express-to-dart --help`
32
+
33
+ ## Architecture & Key Concepts
34
+
35
+ ### Module Organization
36
+
37
+ **bin/cli.js** - Command-line interface
38
+ - Parses CLI arguments and options
39
+ - Routes to appropriate commands (`generate`, `init`, `help`)
40
+ - Handles `--config`, `--help`, `--version` flags
41
+
42
+ **src/index.js** - Main orchestration
43
+ - Exports `generate()` function as primary API
44
+ - Loads config, validates it, calls parser and generator
45
+ - Returns structured result with success/error info
46
+
47
+ **src/config.js** - Configuration management
48
+ - `loadConfig()`: Loads from file or defaults
49
+ - `validateConfig()`: Validates required settings
50
+ - `createDefaultConfigFile()`: Generates template config
51
+ - Includes sensible defaults for all options
52
+
53
+ **src/parser.js** - Route parsing logic
54
+ - `parseFile()`: Extracts routes and sub-routers from a single file
55
+ - `buildRouteTree()`: Recursively builds complete route tree
56
+ - Uses regex to find routes, extracts JSDoc, detects auth/permissions
57
+ - Returns flat list of all routes with full paths
58
+
59
+ **src/generator.js** - Dart code generation
60
+ - `generateDartMethod()`: Creates Dart method for single route
61
+ - `generateApiOptions()`: Creates ApiOptions class
62
+ - `generateServerEndpoints()`: Creates ServerEndpoints class
63
+ - `generateDartFile()`: Combines all into complete Dart file
64
+
65
+ **src/typeMapper.js** - Type mapping
66
+ - `mapType()`: Converts JS/JSDoc types to Dart types
67
+ - `isFileReturnType()`: Detects file download responses
68
+ - Handles basic types, arrays, maps, and custom types
69
+
70
+ **src/utils.js** - Utility functions
71
+ - `generateMethodName()`: Converts routes to camelCase method names
72
+ - `extractNearestJsDoc()`: Finds JSDoc before routes
73
+ - `parseJsDocLine()`: Parses individual JSDoc lines
74
+ - `normalizePermission()`: Converts permission names
75
+ - Helper validators and type checks
76
+
77
+ ### Core Generation Flow
78
+
79
+ 1. **Configuration Loading** (config.js):
80
+ - Loads from provided path, CWD, or defaults
81
+ - Validates required fields
82
+ - Merges user config with defaults
83
+
84
+ 2. **Route Discovery** (parser.js):
85
+ - Entry point is `routes/api.js`
86
+ - Uses regex to find all router definitions
87
+ - Extracts nearest JSDoc comment for each route
88
+ - Detects router-level authentication
89
+ - Recursively processes sub-routers via `router.use()`
90
+ - Handles array-based route definitions
91
+ - Returns flat tree of all routes with full paths
92
+
93
+ 3. **JSDoc Extraction** (parser.js, utils.js):
94
+ - Parses `@var {type} paramName` for parameters
95
+ - Parses `@returns {type}` for return types
96
+ - Parses `@deprecated` for deprecation
97
+ - Infers parameter location (path/query/body)
98
+ - Supports explicit location prefixes (req.body., req.query., req.params.)
99
+
100
+ 4. **Authentication & Permissions** (parser.js):
101
+ - Detects `router.use(authenticateToken)`
102
+ - Finds `PermissionsMiddleware([...])`
103
+ - Normalizes `NsUserPermissions.*` → `NsPermissions.*`
104
+ - Inherits auth/permissions down route tree
105
+
106
+ 5. **Type Mapping** (typeMapper.js):
107
+ - Basic types: string, number, boolean, int
108
+ - Special types: file, date, datetime
109
+ - Collections: string[], list<T>, array<T>, map<K, V>
110
+ - Custom types pass through unchanged
111
+
112
+ 6. **Code Generation** (generator.js):
113
+ - Creates Dart method for each route
114
+ - Handles path/query/body parameters
115
+ - Generates file upload/download code
116
+ - Includes permission checks
117
+ - Builds proper API call statements
118
+
119
+ ### Generated Output
120
+
121
+ **ServerEndpoints.dart** contains:
122
+ - Class with static methods for each API endpoint
123
+ - Method names from paths: `/users/:id/posts` → `usersById_posts()`
124
+ - Full JSDoc with source file reference
125
+ - Auth & permission checks
126
+ - Parameter marshalling (body, query, files)
127
+ - Proper HTTP method calls with ApiOptions
128
+ - File download progress callbacks
129
+
130
+ **ApiOptions.dart** class:
131
+ - `reFreshToken`: Force token refresh
132
+ - `cancelToken`: Dio cancellation
133
+ - `onReceiveProgress`/`onSendProgress`: Progress tracking
134
+ - `enableRetry`: Auto-retry logic
135
+ - `skipAuth`: Skip authentication
136
+ - `maxRetries`: Retry count
137
+ - `formData`: Custom FormData
138
+ - `useServerFileName`: Download filename handling
139
+
140
+ ## Type System & JSDoc Conventions
141
+
142
+ ### Parameter Documentation
143
+
144
+ All parameters must be documented with `@var` tags:
145
+
146
+ ```javascript
147
+ /**
148
+ * Get user profile by ID
149
+ * @var {string} userId - The user ID (path parameter)
150
+ * @var {string} includeDetails - Include detailed information (query parameter)
151
+ * @var {object} metadata - Additional metadata object (body parameter)
152
+ */
153
+ router.get('/users/:userId', ...)
154
+ ```
155
+
156
+ The generator infers parameter location from:
157
+ 1. Explicit prefix: `req.body.`, `req.query.`, `req.params.`
158
+ 2. Path presence: `:paramName` in route → path param
159
+ 3. HTTP method: GET → query, POST/PUT/PATCH → body
160
+ 4. Fallback: assume body for non-GET requests
161
+
162
+ ### Return Type & File Downloads
163
+
164
+ Indicate file responses with `@returns {file}`:
165
+
166
+ ```javascript
167
+ /**
168
+ * Download user export
169
+ * @returns {file}
170
+ */
171
+ router.get('/exports/users', ...)
172
+ ```
173
+
174
+ This generates:
175
+ - Extra `savePath` and `useServerFileName` parameters
176
+ - Call to `Api.downloadFile()` instead of regular HTTP methods
177
+ - Progress callback support via `ApiOptions.onReceiveProgress`
178
+
179
+ ### Deprecation
180
+
181
+ Mark deprecated routes:
182
+
183
+ ```javascript
184
+ /**
185
+ * Get legacy user data (deprecated)
186
+ * @deprecated Use getUser instead
187
+ */
188
+ router.get('/legacy/users/:id', ...)
189
+ ```
190
+
191
+ This adds Dart `@Deprecated()` annotation to generated method.
192
+
193
+ ## Code Patterns & Key Implementation Details
194
+
195
+ ### Route Tree Building (src/parser.js)
196
+
197
+ The `buildRouteTree()` function recursively processes:
198
+ 1. Direct routes in current file: `router.get()`, `router.post()`, etc.
199
+ 2. Sub-routers mounted: `router.use(mountPath, routerVar)`
200
+ 3. Array-based definitions: `{path: '...', handler: varName}`
201
+
202
+ Each route inherits from parents:
203
+ - **Authentication**: Merged via OR (parent auth OR route auth = authenticated)
204
+ - **Permissions**: Combined in array (parent permissions + route permissions)
205
+
206
+ ### Method Name Generation (src/utils.js)
207
+
208
+ Routes → camelCase method names:
209
+ - `/users` → `users()`
210
+ - `/users/:id` → `usersById()`
211
+ - `/api/users/:userId/posts` → `usersBy_userId_posts()`
212
+
213
+ Algorithm:
214
+ 1. Strip leading `/`
215
+ 2. Split by `/`
216
+ 3. For each segment:
217
+ - Replace `:paramName` with `by_paramName`
218
+ - Convert to camelCase
219
+ 4. Join with underscores
220
+
221
+ ### Type Mapping (src/typeMapper.js)
222
+
223
+ Handles:
224
+ - Basic types via mapping table
225
+ - Arrays: `string[]`, `list<T>`, `array<T>`
226
+ - Maps: `map<K, V>` parsed and recursively mapped
227
+ - Unknown types: pass through as-is
228
+
229
+ ### JSDoc Extraction (src/utils.js)
230
+
231
+ Uses `extractNearestJsDoc()` to find the closest JSDoc before a route:
232
+ 1. Find all JSDoc blocks before the route definition
233
+ 2. Check only the last one (closest)
234
+ 3. Verify only whitespace between JSDoc and route
235
+ 4. Handle stacked JSDoc blocks (multiple comments)
236
+
237
+ Then `parseJsDocLine()` parses each line for:
238
+ - `@var {type} name [description]` → parameter
239
+ - `@returns {type}` → return type
240
+ - `@deprecated [message]` → deprecation mark
241
+
242
+ ### Middleware Section Isolation (src/parser.js)
243
+
244
+ To correctly extract `PermissionsMiddleware`:
245
+ 1. Find route pattern match end (after closing quote of path)
246
+ 2. Find function body opening brace (`{`)
247
+ 3. Extract everything between these two positions
248
+ 4. Search for `PermissionsMiddleware([...])` only in this section
249
+ 5. Reduces false positives from handler code
250
+
251
+ ## Module Imports & Dependencies
252
+
253
+ Internal module dependencies:
254
+ - `config.js` → (no dependencies on other src modules)
255
+ - `parser.js` → `typeMapper.js`, `utils.js`
256
+ - `generator.js` → `utils.js`
257
+ - `index.js` → `config.js`, `parser.js`, `generator.js`
258
+ - `cli.js` → `index.js`, `config.js`
259
+
260
+ External dependencies:
261
+ - Node.js `fs`, `path` modules only
262
+ - No external npm packages required
263
+
264
+ ## Debugging & Troubleshooting
265
+
266
+ Console output during generation:
267
+ - Config loading status
268
+ - Route count found
269
+ - Generation completion
270
+ - Output file path
271
+ - Warnings for invalid parameters
272
+
273
+ Enable debugging:
274
+ - Check console output for missing routes
275
+ - Verify `api.js` exists and has routes
276
+ - Inspect generated `.dart` file for correct formatting
277
+
278
+ ## Development Guidelines
279
+
280
+ When modifying the code:
281
+ 1. Keep modules focused on single responsibility
282
+ 2. Update corresponding tests if adding features
283
+ 3. Maintain JSDoc comments in source code
284
+ 4. Preserve the modular structure (utils ← generator, parser)
285
+ 5. Add validation for config and parsed data
286
+
287
+ ### Adding New Features
288
+
289
+ **New route type support**: Update regex in `parseFile()` in parser.js
290
+
291
+ **New parameter type**: Add to type mapping table in typeMapper.js
292
+
293
+ **New code generation pattern**: Add function to generator.js, call from generateDartFile()
294
+
295
+ **New config option**: Add to DEFAULT_CONFIG in config.js and validate in validateConfig()
296
+
297
+ **New CLI command**: Add to main() function in bin/cli.js, implement logic in src/
298
+
299
+ ## Performance Considerations
300
+
301
+ - Generation is O(files × routes) - linear with codebase size
302
+ - Regex scanning is efficient for typical route files
303
+ - No caching between runs (stateless for each generation)
304
+ - Sub-router recursion depth depends on nesting (typically 2-3 levels)
package/MIGRATION.md ADDED
@@ -0,0 +1,335 @@
1
+ # Migration Guide: From Standalone Scripts to NPM Package
2
+
3
+ This document explains the transformation from the original standalone scripts to a professional npm package.
4
+
5
+ ## What Changed
6
+
7
+ ### Before (Original Structure)
8
+ ```
9
+ express-to-dart-endpoints-builder/
10
+ ├── EndpointsToDartFull.js # Main code generator (monolithic)
11
+ ├── endPoints.js # Legacy endpoints class generator
12
+ └── endpoints-to-dart.config.json # Configuration file
13
+ ```
14
+
15
+ **Usage:**
16
+ ```bash
17
+ node EndpointsToDartFull.js
18
+ # or
19
+ node endPoints.js
20
+ ```
21
+
22
+ ### After (NPM Package Structure)
23
+ ```
24
+ express-to-dart-endpoints-builder/
25
+ ├── bin/
26
+ │ └── cli.js # CLI entry point
27
+ ├── src/
28
+ │ ├── index.js # Main API export
29
+ │ ├── config.js # Configuration management
30
+ │ ├── parser.js # Route parsing logic
31
+ │ ├── generator.js # Dart code generation
32
+ │ ├── typeMapper.js # Type mapping utilities
33
+ │ └── utils.js # Helper functions
34
+ ├── examples/
35
+ │ ├── example-routes.js # Route examples
36
+ │ ├── example-config.json # Config example
37
+ │ ├── example-usage.dart # Dart usage examples
38
+ │ ├── example-programmatic.js # Node.js API examples
39
+ │ └── README.md # Examples guide
40
+ ├── package.json # NPM package metadata
41
+ ├── README.md # User documentation
42
+ └── CLAUDE.md # Developer documentation
43
+ ```
44
+
45
+ **Usage:**
46
+ ```bash
47
+ # CLI
48
+ express-to-dart generate
49
+ # or
50
+ npm run generate
51
+
52
+ # Programmatic
53
+ const { generate } = require('express-to-dart-endpoints-builder');
54
+ const result = generate();
55
+ ```
56
+
57
+ ## Key Improvements
58
+
59
+ ### 1. **Modular Architecture**
60
+ - Single 700+ line file split into 6 focused modules
61
+ - Each module has a single responsibility
62
+ - Easy to understand, test, and maintain
63
+
64
+ ### 2. **Better Configuration**
65
+ - Default configuration with sensible defaults
66
+ - `express-to-dart init` command to scaffold config
67
+ - `--config` flag to use custom config files
68
+ - Configuration validation and helpful error messages
69
+
70
+ ### 3. **Professional CLI**
71
+ - Standard command structure: `express-to-dart <command>`
72
+ - Help, version, and init commands
73
+ - Proper error handling and exit codes
74
+ - Works globally after `npm install -g`
75
+
76
+ ### 4. **Better Error Handling**
77
+ - Structured error messages
78
+ - Return objects with success/error information
79
+ - Helpful suggestions for common issues
80
+
81
+ ### 5. **Full Documentation**
82
+ - Comprehensive README with examples
83
+ - API documentation with type information
84
+ - CLAUDE.md for future developer context
85
+ - Multiple example files (routes, config, Dart, Node.js)
86
+
87
+ ### 6. **Backward Compatibility**
88
+ - Original EndpointsToDartFull.js still works
89
+ - Legacy endPoints.js still available
90
+ - Default configuration format unchanged
91
+
92
+ ## Functionality Parity
93
+
94
+ All original functionality is preserved:
95
+
96
+ | Feature | Status |
97
+ |---------|--------|
98
+ | JSDoc parsing | ✓ Unchanged |
99
+ | Type mapping | ✓ Unchanged |
100
+ | Route discovery | ✓ Unchanged |
101
+ | Authentication detection | ✓ Unchanged |
102
+ | Permission extraction | ✓ Unchanged |
103
+ | File upload/download handling | ✓ Unchanged |
104
+ | Sub-router traversal | ✓ Unchanged |
105
+ | Deprecation handling | ✓ Unchanged |
106
+ | Dart code generation | ✓ Unchanged |
107
+
108
+ ## Migration Steps
109
+
110
+ ### For Existing Projects
111
+
112
+ **Step 1: Update your workflow**
113
+
114
+ Instead of:
115
+ ```bash
116
+ node EndpointsToDartFull.js
117
+ ```
118
+
119
+ Use:
120
+ ```bash
121
+ npm run generate
122
+ # or
123
+ express-to-dart
124
+ ```
125
+
126
+ **Step 2: Verify configuration**
127
+
128
+ Your existing `endpoints-to-dart.config.json` works as-is. No changes needed!
129
+
130
+ **Step 3: Review generated output**
131
+
132
+ Generated Dart code is identical to before. No changes to your Dart code needed!
133
+
134
+ ### For New Projects
135
+
136
+ **Step 1: Install**
137
+ ```bash
138
+ npm install express-to-dart-endpoints-builder
139
+ ```
140
+
141
+ **Step 2: Initialize**
142
+ ```bash
143
+ express-to-dart init
144
+ # Creates endpoints-to-dart.config.json
145
+ ```
146
+
147
+ **Step 3: Configure**
148
+ Edit `endpoints-to-dart.config.json` with your paths
149
+
150
+ **Step 4: Generate**
151
+ ```bash
152
+ npm run generate
153
+ ```
154
+
155
+ ## API Changes
156
+
157
+ ### CLI
158
+
159
+ **Old:**
160
+ ```bash
161
+ node EndpointsToDartFull.js # Always generated
162
+ node endPoints.js # Legacy class only
163
+ ```
164
+
165
+ **New:**
166
+ ```bash
167
+ express-to-dart # Default: generate
168
+ express-to-dart generate # Explicit generate
169
+ express-to-dart init # Initialize config
170
+ express-to-dart --help # Show help
171
+ express-to-dart --version # Show version
172
+ express-to-dart generate --config ./config.json
173
+ ```
174
+
175
+ ### Programmatic API
176
+
177
+ **Old:**
178
+ ```javascript
179
+ // Had to require specific modules and call functions
180
+ require('./EndpointsToDartFull.js');
181
+ // or
182
+ const { buildEndPointsClass } = require('./endPoints.js');
183
+ ```
184
+
185
+ **New:**
186
+ ```javascript
187
+ const { generate, loadConfig, validateConfig } =
188
+ require('express-to-dart-endpoints-builder');
189
+
190
+ // Simple one-liner
191
+ const result = generate();
192
+
193
+ // Or with custom config
194
+ const result = generate('./config.json');
195
+
196
+ // With result object
197
+ if (result.success) {
198
+ console.log(`Generated ${result.count} endpoints`);
199
+ console.log(`Saved to: ${result.outputPath}`);
200
+ result.routes.forEach(route => {
201
+ console.log(`${route.method} ${route.fullPath}`);
202
+ });
203
+ }
204
+ ```
205
+
206
+ ## Configuration Changes
207
+
208
+ No breaking changes! Your existing config file works as-is.
209
+
210
+ **New optional fields:**
211
+ ```json
212
+ {
213
+ "classNameEndpoints": "ServerEndpoints" // Default class name (was hardcoded)
214
+ }
215
+ ```
216
+
217
+ **All existing fields still supported:**
218
+ - `routesDir`
219
+ - `outputDir`
220
+ - `baseUrl`
221
+ - `apiClassName`
222
+ - `imports`
223
+ - `includePatterns`
224
+ - `excludePatterns`
225
+
226
+ ## File Structure Mapping
227
+
228
+ | Original | New Location | Purpose |
229
+ |----------|--------------|---------|
230
+ | EndpointsToDartFull.js (main logic) | src/parser.js | Route parsing |
231
+ | EndpointsToDartFull.js (types) | src/typeMapper.js | Type conversion |
232
+ | EndpointsToDartFull.js (generation) | src/generator.js | Dart code generation |
233
+ | EndpointsToDartFull.js (utils) | src/utils.js | Helper functions |
234
+ | (new) | src/config.js | Config management |
235
+ | (new) | src/index.js | Main export |
236
+ | (new) | bin/cli.js | CLI interface |
237
+
238
+ ## Testing
239
+
240
+ All functionality has been tested:
241
+
242
+ ✓ Type mapping (string, number, arrays, maps, custom types)
243
+ ✓ Method name generation (camelCase conversion)
244
+ ✓ Parameter validation and detection
245
+ ✓ JSDoc parsing and extraction
246
+ ✓ Configuration loading with defaults
247
+ ✓ CLI help and version commands
248
+ ✓ Error handling and reporting
249
+
250
+ ## Performance
251
+
252
+ **No change in performance.** The refactored code:
253
+ - Uses the same algorithms
254
+ - Has the same time complexity: O(files × routes)
255
+ - Maintains stateless generation
256
+ - Supports sub-router recursion
257
+
258
+ ## Package.json Scripts
259
+
260
+ ```json
261
+ {
262
+ "scripts": {
263
+ "start": "node bin/cli.js",
264
+ "generate": "node bin/cli.js generate",
265
+ "init": "node bin/cli.js init"
266
+ }
267
+ }
268
+ ```
269
+
270
+ **Usage:**
271
+ ```bash
272
+ npm run generate # Generate Dart code
273
+ npm run init # Create config template
274
+ npm start # Run CLI (shows help)
275
+ ```
276
+
277
+ ## Backward Compatibility
278
+
279
+ The original files still exist and work:
280
+
281
+ ```bash
282
+ # Still works
283
+ node EndpointsToDartFull.js
284
+ node endPoints.js
285
+ ```
286
+
287
+ They have NOT been removed or modified, so existing scripts/workflows continue to function.
288
+
289
+ ## What's New
290
+
291
+ ### For Users
292
+
293
+ 1. **Easy installation**: `npm install -g express-to-dart-endpoints-builder`
294
+ 2. **Simple commands**: `express-to-dart generate`
295
+ 3. **Better error messages**: Clear guidance on fixing issues
296
+ 4. **Documentation**: Comprehensive README and examples
297
+ 5. **Configuration template**: `express-to-dart init` creates starter config
298
+
299
+ ### For Developers
300
+
301
+ 1. **Modular code**: Easy to understand, extend, and test
302
+ 2. **Clear separation**: Each module has one job
303
+ 3. **Developer docs**: CLAUDE.md explains architecture
304
+ 4. **Examples**: Multiple examples in examples/ directory
305
+ 5. **Better errors**: Helpful error objects with context
306
+
307
+ ## Deprecations
308
+
309
+ None! All original features are supported.
310
+
311
+ The original standalone scripts are still available but the new package is the recommended approach for:
312
+ - New projects
313
+ - Developers who want to use it as a Node.js module
314
+ - CI/CD integration
315
+ - Global CLI tool
316
+ - Distribution via npm
317
+
318
+ ## Support
319
+
320
+ - **README.md** - User-facing documentation
321
+ - **CLAUDE.md** - Developer documentation
322
+ - **examples/** - Code examples
323
+ - **GitHub Issues** - Report bugs and request features
324
+
325
+ ## Questions?
326
+
327
+ Refer to:
328
+ 1. **README.md** - Comprehensive user guide
329
+ 2. **examples/README.md** - Practical examples
330
+ 3. **CLAUDE.md** - Architecture and implementation
331
+ 4. **examples/example-programmatic.js** - Integration examples
332
+
333
+ ---
334
+
335
+ **All original functionality preserved. All new features are additive. Zero breaking changes.**