@yesprasad/fluent-graph 0.2.0 → 0.2.2

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 CHANGED
@@ -2,8 +2,6 @@
2
2
 
3
3
  **Dependency visibility and impact analysis for ServiceNow Fluent SDK projects.**
4
4
 
5
- **Catch breaking changes before deployment by mapping hidden relationships between tables, fields, scripts, and UI actions.**
6
-
7
5
  ---
8
6
 
9
7
  ## The Problem
@@ -14,286 +12,120 @@ You're refactoring a ServiceNow custom table. You delete a field. You deploy.
14
12
 
15
13
  14 client scripts fail. 3 business rules error out. 2 dashboards go blank.
16
14
 
17
- **You realise the breaking changes at runtime in production instance.**
15
+ **You discover the breaking changes at runtime in production.**
18
16
 
19
17
  ---
18
+
20
19
  ## The Solution
21
- **Welcome to Fluent-Graph**
22
20
 
23
- `fluent-graph` observes the ServiceNow SDK's internal compilation process to extract dependency graphs, detect identity conflicts, and perform blast-radius analysiswithout modifying your source code or re-parsing Fluent DSL.
21
+ `fluent-graph` maps every dependency in your Fluent SDK project tables, fields, scripts, business rules, flows, catalog itemsso you know what breaks *before* you deploy.
22
+
23
+ ```bash
24
+ npx @yesprasad/fluent-graph blast incident
25
+ ```
24
26
 
25
- run - npx @yesprasad/fluent-graph blast incident
26
- **Output:**
27
27
  ```
28
28
  🔥 BLAST RADIUS ANALYSIS
29
29
  Target: incident
30
30
 
31
31
  ⚠️ 3 artifacts will break if you modify this table:
32
- • bank_incident_onload (Client Script)
33
- • cs_incident_onload (Client Script)
34
- • cs_incident_onchange_caller (Client Script)
32
+ • bank_incident_onload (Client Script)
33
+ • cs_incident_onload (Client Script)
34
+ • cs_incident_onchange_caller (Client Script)
35
35
  ```
36
36
 
37
- 🔥 **Now you know before you deploy.**
37
+ **Now you know before you deploy.**
38
38
 
39
39
  ---
40
40
 
41
-
42
- ## What It Does
43
-
44
- - **Extracts artifact lineage** from SDK projects (tables, columns, scripts, business rules)
45
- - **Detects identity conflicts** (duplicate `$id` declarations across files)
46
- - **Maps relationships** (foreign keys, table extensions, logic attachments)
47
- - **Generates blast-radius reports** (what breaks if you change X?)
48
- - **Outputs machine-readable JSON** for CI/CD integration
49
-
50
- ---
51
41
  ## Installation
52
42
 
53
- **Prerequisites:**
54
- - Node.js 18+
55
- - An existing ServiceNow Fluent SDK project with `@servicenow/sdk` installed
43
+ Requires Node.js 18+ and an existing Fluent SDK project with `@servicenow/sdk` installed.
56
44
 
57
- **Install globally:**
45
+ **Global install:**
58
46
  ```bash
59
47
  npm install -g @yesprasad/fluent-graph
60
48
  ```
61
- **basic CLI usage:**
62
- ```bash
63
- fluent-graph analyze
64
- fluent-graph blast <table_name or artifact_name>
65
- ```
66
49
 
67
- **Or use directly with npx (no installation needed):**
50
+ **Or use without installing:**
68
51
  ```bash
69
- cd your-fluent-project
70
- npx @yesprasad/fluent-graph extract
52
+ npx @yesprasad/fluent-graph analyze
71
53
  ```
72
54
 
73
- **Verify installation:**
74
- ```bash
75
- fluent-graph --version
76
- ```
77
55
  ---
78
56
 
79
- ## Usage
57
+ ## Commands
58
+
59
+ ### Analyze — full project lineage map
60
+
61
+ ```bash
62
+ fluent-graph analyze
63
+ ```
80
64
 
65
+ Scans your project and prints a grouped summary of all artifacts and their relationships:
81
66
 
82
- **Output:**
83
67
  ```
84
68
  ✔ Workspace SDK loaded
85
69
  ✔ Project loaded
86
70
  ✔ Graph built: 181 nodes, 141 edges
87
71
 
88
72
  📊 LINEAGE MAP
89
- ────────────────────────────────────────────────────────────
90
-
91
- 📦 DATA SCHEMA
92
- ┌─────────────────────────────────────────────┬───────────────┐
93
- │ Table │ Status │
94
- ├─────────────────────────────────────────────┼───────────────┤
95
- │ x_1566039_seventh_critical_account │ [ACTIVE] │
96
- │ x_1566039_seventh_critical_account_incident_ext │ [ACTIVE] │
97
- │ x_1566039_seventh_customer │ [ACTIVE] │
98
- │ x_1566039_seventh_account │ [ACTIVE] │
99
- │ x_1566039_seventh_fraud_alert │ [ACTIVE] │
100
- │ x_1566039_seventh_risk_score │ [ACTIVE] │
101
- │ x_1566039_seventh_call_case │ [ACTIVE] │
102
- │ x_1566039_seventh_compliance_flag │ [ACTIVE] │
103
- │ x_1566039_seventh_account_extension │ [ACTIVE] │
104
- └─────────────────────────────────────────────┴───────────────┘
105
-
106
- 🔗 SCHEMA RELATIONSHIPS (Reference Fields)
107
- ┌─────────────────────────────────────────────┬───────────────────┬─────────────────────────────┐
108
- │ Table │ Field │ Target Table │
109
- ├─────────────────────────────────────────────┼───────────────────┼─────────────────────────────┤
110
- │ x_1566039_seventh_critical_account │ assigned_team │ sys_user_group │
111
- │ x_1566039_seventh_critical_account_incident_ext │ bank_account │ x_bank_critical_account │
112
- │ x_1566039_seventh_account │ owner │ x_1566039_seventh_customer │
113
- │ x_1566039_seventh_fraud_alert │ account │ x_1566039_seventh_account │
114
- │ x_1566039_seventh_risk_score │ account │ x_1566039_seventh_account │
115
- │ x_1566039_seventh_call_case │ customer │ x_1566039_seventh_customer │
116
- │ x_1566039_seventh_compliance_flag │ customer │ x_1566039_seventh_customer │
117
- │ x_1566039_seventh_account_extension │ linked_account │ x_1566039_seventh_account │
118
- └─────────────────────────────────────────────┴───────────────────┴─────────────────────────────┘
119
-
120
- ⚙️ LOGIC ATTACHMENTS (Scripts & Actions)
121
- ┌─────────┬────────────────────────────────────┬───────────────────────────────────────────────┬──────────────┬──────────────────┐
122
- │ (index) │ Name │ Table │ Type │ Artifact Type │
123
- ├─────────┼────────────────────────────────────┼───────────────────────────────────────────────┼──────────────┼──────────────────┤
124
- │ 0 │ bank_incident_onload │ incident │ [onLoad] │ script client │
125
- │ 1 │ bank_account_onchange │ x_1566039_seventh_critical_account │ [onChange] │ script client │
126
- │ 2 │ cs_task_onload │ task │ [onLoad] │ script client │
127
- │ 3 │ cs_task_onchange_priority │ x_1566039_seventh_critical_account_incident_ext │ [onChange] │ script client │
128
- │ 4 │ cs_incident_onload │ incident │ [onLoad] │ script client │
129
- │ 5 │ cs_incident_onchange_caller │ incident │ [onChange] │ script client │
130
- │ 6 │ cs_account_onchange_type │ x_1566039_seventh_account │ [onChange] │ script client │
131
- │ 7 │ cs_alert_onload │ x_1566039_seventh_fraud_alert │ [onLoad] │ script client │
132
- │ 8 │ cs_risk_onchange_score │ x_1566039_seventh_risk_score │ [onChange] │ script client │
133
- │ 9 │ Auto-close empty Change Requests │ change_request │ [action] │ script │
134
- │ 10 │ View car info │ x_snc_ts_custom_cars │ [action] │ ui action │
135
- │ 11 │ SampleScriptInclude │ [global] │ [action] │ script include │
136
- └─────────┴────────────────────────────────────┴───────────────────────────────────────────────┴──────────────┴──────────────────┘
137
-
138
- 🔒 SECURITY & ACCESS (ACLs)
139
- ┌──────────────────────────────┬───────────────────────┬───────────────────────────┐
140
- │ ACL │ Level / Roles │ Table │
141
- ├──────────────────────────────┼───────────────────────┼───────────────────────────┤
142
- │ DELETE on task.description │ Field-level,
143
- Roles: 58794a2b937f4c0eba394fce1515930e, ae7beff0df584bd7a39fac26deaf20b7 │ task │
144
- └──────────────────────────────┴───────────────────────┴───────────────────────────┘
145
73
 
146
- 🧠 PROJECT INSIGHTS
147
- • Total User Artifacts: 23
148
- User Artifacts Breakdown:
149
- {
150
- "sys_script_client": 9,
151
- "sys_db_object": 10,
152
- "sys_script": 1,
153
- "sys_security_acl": 1,
154
- "sys_ui_action": 1,
155
- "sys_script_include": 1
156
- }
157
- • Platform Dependencies: 9
158
- • Internal References: 132
159
- • Total Artifacts: 181
160
- • Total Relationships: 141
74
+ Client Script 9 artifacts
75
+ Table 10 artifacts
76
+ Business Rule 1 artifact
77
+ Flow Definition 1 artifact
78
+ Catalog Item 2 artifacts
79
+ Acl 1 artifact
80
+ Ui Action 1 artifact
161
81
 
82
+ 🧠 PROJECT INSIGHTS
83
+ Total User Artifacts: 35
84
+ Platform Dependencies: 9
85
+ Total Relationships: 141
162
86
  ```
163
87
 
164
- **Generated file:** `fluent-graph.json` (in project root)
88
+ Also writes `fluent-graph.json` to your project root for CI/CD or tooling use.
165
89
 
166
90
  ---
167
91
 
168
- ### Blast Radius Analysis
169
-
170
- Analyze the impact of changing a specific table:
92
+ ### Blast impact analysis for a specific artifact
171
93
 
172
94
  ```bash
173
- fluent-graph blast incident
95
+ fluent-graph blast <table_or_artifact_name>
174
96
  ```
175
97
 
176
- **Output:**
98
+ Example:
99
+ ```bash
100
+ fluent-graph blast x_1566039_seventh_customer
177
101
  ```
178
- [FLUENT-GRAPH] BLAST RADIUS REPORT
179
- Target: incident [sys_db_object]
180
- SysID: 26441130e60544259e930cb385f74fca
181
- =========================================================================================
182
-
183
- ┌──────────────────────────┬─────────────────┬──────────────────────────────┬─────────────────────────────────┬──────────────────────┐
184
- │ Impacted Artifact │ Type │ File │ Reason │ State │
185
- ├──────────────────────────┼─────────────────┼──────────────────────────────┼─────────────────────────────────┼──────────────────────┤
186
- │ bank_incident_onload │ client_script │ src/fluent/bank_small_... │ ⚡ Logic Attachment [onLoad] │ INSERT_OR_UPDATE │
187
- │ cs_incident_onload │ client_script │ src/fluent/client-scripts... │ ⚡ Logic Attachment [onLoad] │ INSERT_OR_UPDATE │
188
- │ cs_incident_onchange_... │ client_script │ src/fluent/client-scripts... │ ⚡ Logic Attachment [onChange] │ INSERT_OR_UPDATE │
189
- └──────────────────────────┴─────────────────┴──────────────────────────────┴─────────────────────────────────┴──────────────────────┘
190
102
 
191
- ⚠️ PRE-DEPLOYMENT SUMMARY
192
- - Total Impacted: 3 artifacts
193
- - Breakdown:
194
- • client_script: 3
195
103
  ```
104
+ [FLUENT-GRAPH] BLAST RADIUS REPORT
105
+ Target: x_1566039_seventh_customer
196
106
 
197
- ---
107
+ ┌────────────────────────────────┬───────────────────┬──────────────────────────────┐
108
+ │ Impacted Artifact │ Type │ Reason │
109
+ ├────────────────────────────────┼───────────────────┼──────────────────────────────┤
110
+ │ x_1566039_seventh_account │ table │ Reference field: owner │
111
+ │ x_1566039_seventh_call_case │ table │ Reference field: customer │
112
+ │ cs_account_onchange_type │ client_script │ Logic attachment │
113
+ └────────────────────────────────┴───────────────────┴──────────────────────────────┘
198
114
 
199
- ## Output Format
200
-
201
- The generated `fluent-graph.json` contains:
202
-
203
- ```json
204
- {
205
- "metadata": {
206
- "projectRoot": "/path/to/project",
207
- "scopeId": "59760b6f783848bd981362d6b1d0c7ed",
208
- "scopeName": "x_1566039_seventh",
209
- "recordCount": 171,
210
- "referenceCount": 15,
211
- "compositionCount": 111,
212
- "generatedAt": "2025-01-04T16:32:54.130Z",
213
- "sdkVersion": "4.1.0"
214
- },
215
- "nodes": [
216
- {
217
- "id": "6eed3050f8214b6194056935182d9fa5",
218
- "table": "sys_db_object",
219
- "name": "x_1566039_seventh_customer",
220
- "label": "Customer",
221
- "action": "INSERT_OR_UPDATE",
222
- "attributes": {
223
- "access": "public",
224
- "is_extendable": false,
225
- "read_access": true
226
- },
227
- "source": {
228
- "file": "src/fluent/bank_small_artifacts.now.ts",
229
- "type": "VariableStatement"
230
- }
231
- }
232
- ],
233
- "edges": [
234
- {
235
- "from": "4da5b7b689ae43e69b3db1bfe1dd0cd5",
236
- "to": "0fc60d0f1c35401580488c83440a4d81",
237
- "via": "owner",
238
- "type": "reference",
239
- "targetTable": "x_1566039_seventh_customer"
240
- }
241
- ]
242
- }
115
+ ⚠️ PRE-DEPLOYMENT SUMMARY
116
+ Total Impacted: 3 artifacts
243
117
  ```
244
118
 
245
- ### Node Types
246
-
247
- | `table` Value | Description |
248
- |---------------|-------------|
249
- | `sys_db_object` | Database table definition |
250
- | `sys_dictionary` | Column/field definition |
251
- | `sys_script_client` | Client script (onLoad, onChange, etc.) |
252
- | `sys_script` | Business rule |
253
- | `sys_choice` | Choice list value |
254
-
255
- ### Edge Types
256
-
257
- | `type` | Description |
258
- |--------|-------------|
259
- | `reference` | Foreign key or logic attachment |
260
- | `composition` | Parent-child relationship (e.g., table → columns) |
261
-
262
119
  ---
263
120
 
264
- ## How It Works
265
-
266
- `fluent-graph` does **not** parse your TypeScript/Fluent code directly.
267
-
268
- Instead, it:
269
-
270
- 1. **Locates the SDK** installed in `node_modules/@servicenow/sdk`
271
- 2. **Loads your Fluent project** using the SDK's internal `Project` API
272
- 3. **Observes SDK compilation** to extract already-parsed artifacts
273
- 4. **Builds a dependency graph** from SDK-provided metadata
274
- 5. **Outputs structured JSON** for analysis or automation
275
-
276
- This approach:
277
- - ✅ Works across SDK versions (no brittle AST parsing)
278
- - ✅ Captures runtime behavior (e.g., dynamic references)
279
- - ✅ Stays synchronized with SDK semantics
280
-
281
- ---
282
-
283
- ## Use Cases
284
-
285
- ### 1. Pre-Deployment Impact Analysis
286
- ```bash
287
- fluent-graph blast incident > pre-deploy-report.txt
288
- ```
121
+ ## CI/CD Integration
289
122
 
290
- ### 2. CI/CD Integration
291
123
  ```yaml
292
124
  # .github/workflows/fluent-check.yml
293
- - name: Extract lineage
294
- run: npx fluent-graph analyze
125
+ - name: Analyze lineage
126
+ run: npx @yesprasad/fluent-graph analyze
295
127
 
296
- - name: Check for conflicts
128
+ - name: Fail on identity conflicts
297
129
  run: |
298
130
  if grep -q '"action": "CONFLICT"' fluent-graph.json; then
299
131
  echo "❌ Identity conflicts detected"
@@ -301,92 +133,19 @@ fluent-graph blast incident > pre-deploy-report.txt
301
133
  fi
302
134
  ```
303
135
 
304
- ### 3. Documentation Generation
305
- Parse `fluent-graph.json` to auto-generate:
306
- - Schema diagrams
307
- - Dependency matrices
308
- - Change impact reports
309
-
310
136
  ---
311
137
 
312
- ## Performance
313
-
314
- Typical extraction times on SDK 4.1.x:
315
-
316
- | Project Size | Artifacts | Extraction Time |
317
- |--------------|-----------|-----------------|
318
- | Small | 50-100 | < 5 seconds |
319
- | Medium | 100-500 | 5-10 seconds |
320
- | Large | 500-1000 | 10-20 seconds |
321
- | Enterprise | 1000+ | 20-30 seconds |
322
-
323
- *Times measured on MacBook Air M1, 16GB RAM and approximated*
324
-
325
-
326
138
  ## Limitations
327
139
 
328
- ### Current Version (v0.1)
329
-
330
- - **Schema relationships detection incomplete:** The extractor currently captures foreign key relationships declared in `sys_dictionary` records, but some Fluent DSL references (e.g., `ReferenceColumn` in Table definitions) may not appear in edges if the SDK's internal representation doesn't expose them during the observed compilation phase.
331
-
332
- - **Tested against SDK 4.1.x only:** While the architecture is designed to handle SDK evolution, version-specific parsing has only been validated with `@servicenow/sdk@4.1.0`. Newer or older versions may produce incomplete graphs.
333
-
334
- - **No UI visualization:** Output is JSON-only. Use external tools (e.g., D3.js, Mermaid) to render graphs.
335
-
336
- - **Single-project scope:** Does not analyze cross-scope dependencies (e.g., references to `global` tables outside your app scope).
337
-
338
- ---
339
-
340
- ## Roadmap
341
-
342
- - [ ] Improve FK edge extraction: Currently misses some ReferenceColumn relationships when table nodes don't exist
343
- - [ ] Add ACL/UI Policy/UI Action support to blast radius
344
- - [ ] Support SDK 4.0.x (test against 3 versions: 4.0, 4.1, 4.2)
345
- - [ ] HTML report with interactive D3.js graph visualization
346
- - [ ] `--watch` mode: Re-extract on file changes during development
347
- - [ ] Cross-scope analysis: Detect dependencies on global/platform apps
348
- - [ ] Adding unit test cases
349
-
350
- ---
351
-
352
- ### Development Setup
353
- ```bash
354
- git clone https://github.com/yesprasad/fluent-graph
355
- cd fluent-graph
356
- npm install
357
- npm run build
358
-
359
- # Test against example project
360
- cd ../your-fluent-project
361
- npx /path/to/fluent-graph/dist/cli/index.js extract
362
- ```
363
-
364
- ### Running Tests
365
- ```bash
366
- npm test # Add Unit tests
367
- npm run test:integration # Test against real SDK project
368
- ```
140
+ - Tested against `@servicenow/sdk@4.5.x`
141
+ - No UI visualization — output is JSON and terminal only
142
+ - Single-project scope does not trace cross-scope dependencies
369
143
 
370
144
  ---
371
145
 
372
146
  ## License
373
- MIT License
374
-
375
- Copyright (c) 2026 Eshwar Sowbhagya Prasad Yaddanapudi.
376
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
377
-
378
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
379
-
380
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
381
-
382
-
383
- ---
384
-
385
- ## Author
386
-
387
- **Eshwar Sowbhagya Prasad Yaddanapudi**
388
147
 
389
- Built with focus on making ServiceNow Pro Developer Fluent development with now-sdk safer, faster, and more transparent.
148
+ MIT License Copyright (c) 2026 Eshwar Sowbhagya Prasad Yaddanapudi
390
149
 
391
150
  ---
392
151
 
@@ -405,4 +164,10 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
405
164
 
406
165
  ---
407
166
 
408
- **Questions or issues?** Open an issue on GitHub or reach out directly.
167
+ **Questions or issues?** Open an issue on GitHub or reach out directly.
168
+
169
+ ## Author
170
+
171
+ **Eshwar Sowbhagya Prasad Yaddanapudi**
172
+
173
+ Questions or issues? [Open an issue on GitHub](https://github.com/yesprasad/fluent-graph/issues)
@@ -56,6 +56,7 @@ exports.blastCommand = new commander_1.Command('blast')
56
56
  .option('--include-deleted', 'Include deleted artifacts in the analysis')
57
57
  .option('--no-banner', 'Skip banner (inherited)')
58
58
  .action(async (targetTableName, options) => {
59
+ const isJson = options.format === 'json';
59
60
  try {
60
61
  const graphFilePath = path.isAbsolute(options.graph)
61
62
  ? options.graph
@@ -67,7 +68,12 @@ exports.blastCommand = new commander_1.Command('blast')
67
68
  registry.load(sdkDetection.sdkPath);
68
69
  }
69
70
  if (!fs.existsSync(graphFilePath)) {
70
- console.error(chalk_1.default.red(`\n❌ Error: Graph file not found at ${graphFilePath}`));
71
+ if (isJson) {
72
+ console.log(JSON.stringify({ error: `Graph file not found at ${graphFilePath}`, code: 'GRAPH_NOT_FOUND' }));
73
+ }
74
+ else {
75
+ console.error(chalk_1.default.red(`\n❌ Error: Graph file not found at ${graphFilePath}`));
76
+ }
71
77
  process.exit(1);
72
78
  }
73
79
  const lineageGraph = JSON.parse(fs.readFileSync(graphFilePath, 'utf8'));
@@ -77,28 +83,40 @@ exports.blastCommand = new commander_1.Command('blast')
77
83
  const isBaseTable = !targetNode;
78
84
  const isTargetReferenced = lineageGraph.edges.some(edge => edge.to === targetNodeId || edge.targetTable === targetTableName);
79
85
  if (!targetNode && !isTargetReferenced) {
80
- console.log(chalk_1.default.red(`\n❌ Target "${targetTableName}" not found or referenced`));
81
- console.log(chalk_1.default.yellow('\n💡 Available custom tables:'));
82
86
  const customTables = lineageGraph.nodes
83
87
  .filter(node => registry.getPluginName(node.table) === 'TablePlugin' && !registry.isChild(node.table) && node.action !== 'DELETE')
84
88
  .map(node => node.name)
85
89
  .sort();
86
- customTables.forEach(tableName => console.log(chalk_1.default.gray(' • ') + chalk_1.default.white(tableName)));
87
- console.log(chalk_1.default.yellow('\n💡 Referenced platform tables:'));
88
90
  const platformTables = [...new Set(lineageGraph.edges
89
91
  .filter(edge => edge.to.startsWith('platform:'))
90
92
  .map(edge => edge.to.split(':')[1]))].sort();
91
- platformTables.forEach(tableName => console.log(chalk_1.default.gray(' • ') + chalk_1.default.magenta(tableName)));
93
+ if (isJson) {
94
+ console.log(JSON.stringify({
95
+ error: `Target "${targetTableName}" not found or referenced`,
96
+ code: 'TARGET_NOT_FOUND',
97
+ availableCustomTables: customTables,
98
+ availablePlatformTables: platformTables,
99
+ }));
100
+ }
101
+ else {
102
+ console.log(chalk_1.default.red(`\n❌ Target "${targetTableName}" not found or referenced`));
103
+ console.log(chalk_1.default.yellow('\n💡 Available custom tables:'));
104
+ customTables.forEach(tableName => console.log(chalk_1.default.gray(' • ') + chalk_1.default.white(tableName)));
105
+ console.log(chalk_1.default.yellow('\n💡 Referenced platform tables:'));
106
+ platformTables.forEach(tableName => console.log(chalk_1.default.gray(' • ') + chalk_1.default.magenta(tableName)));
107
+ }
92
108
  process.exit(1);
93
109
  }
94
110
  // ── STEP 2: Display header ───────────────────────────────────────────────
95
- console.log(chalk_1.default.yellow.bold('\n🔥 BLAST RADIUS ANALYSIS'));
96
- console.log(chalk_1.default.gray(''.repeat(80)));
97
- console.log(chalk_1.default.gray('Target: ') + chalk_1.default.white(targetTableName) + (isBaseTable ? chalk_1.default.yellow(' [Base Table]') : ''));
98
- if (!isBaseTable) {
99
- console.log(chalk_1.default.gray('File: ') + chalk_1.default.gray(targetNode.source.file));
111
+ if (!isJson) {
112
+ console.log(chalk_1.default.yellow.bold('\n🔥 BLAST RADIUS ANALYSIS'));
113
+ console.log(chalk_1.default.gray(''.repeat(80)));
114
+ console.log(chalk_1.default.gray('Target: ') + chalk_1.default.white(targetTableName) + (isBaseTable ? chalk_1.default.yellow(' [Base Table]') : ''));
115
+ if (!isBaseTable) {
116
+ console.log(chalk_1.default.gray('File: ') + chalk_1.default.gray(targetNode.source.file));
117
+ }
118
+ console.log(chalk_1.default.gray('═'.repeat(80)));
100
119
  }
101
- console.log(chalk_1.default.gray('═'.repeat(80)));
102
120
  // ── STEP 3: BFS traversal ────────────────────────────────────────────────
103
121
  const maxDepth = options.directOnly ? 1 : Math.max(1, parseInt(options.depth, 10) || 10);
104
122
  const traversal = (0, traversal_1.traverseBlastRadius)(lineageGraph, targetTableName, maxDepth);
@@ -119,23 +137,49 @@ exports.blastCommand = new commander_1.Command('blast')
119
137
  const directImpact = displayed.filter(tn => tn.hop === 1);
120
138
  const transitiveImpact = displayed.filter(tn => tn.hop > 1);
121
139
  if (displayed.length === 0) {
122
- console.log(chalk_1.default.green('\n✅ Zero dependencies detected in local project.\n'));
140
+ if (isJson) {
141
+ console.log(JSON.stringify({
142
+ target: targetTableName,
143
+ isBaseTable,
144
+ totalImpacted: 0,
145
+ direct: 0,
146
+ transitive: 0,
147
+ maxHopReached: 0,
148
+ cyclesPrevented: traversal.cyclesPrevented,
149
+ riskLevel: 'LOW',
150
+ impacts: [],
151
+ }, null, 2));
152
+ }
153
+ else {
154
+ console.log(chalk_1.default.green('\n✅ Zero dependencies detected in local project.\n'));
155
+ }
123
156
  return;
124
157
  }
125
158
  // ── STEP 5: Output ───────────────────────────────────────────────────────
126
159
  switch (options.format) {
127
160
  case 'json': {
128
- const output = displayed.map(tn => ({
129
- artifact: tn.node.name,
130
- type: registry.getDisplayGroupName(tn.node.table).toLowerCase(),
131
- file: tn.node.source.file,
132
- hop: tn.hop,
133
- path: tn.path,
134
- via: tn.viaEdge.via ?? tn.viaEdge.type,
135
- edgeType: tn.viaEdge.type,
136
- state: tn.node.action,
137
- }));
138
- console.log(JSON.stringify(output, null, 2));
161
+ const totalCount = displayed.length;
162
+ const riskLevel = totalCount < 3 ? 'LOW' : totalCount < 8 ? 'MEDIUM' : 'HIGH';
163
+ console.log(JSON.stringify({
164
+ target: targetTableName,
165
+ isBaseTable,
166
+ totalImpacted: totalCount,
167
+ direct: directImpact.length,
168
+ transitive: transitiveImpact.length,
169
+ maxHopReached: traversal.maxHopReached,
170
+ cyclesPrevented: traversal.cyclesPrevented,
171
+ riskLevel,
172
+ impacts: displayed.map(tn => ({
173
+ artifact: tn.node.name,
174
+ type: registry.getDisplayGroupName(tn.node.table).toLowerCase(),
175
+ file: tn.node.source.file,
176
+ hop: tn.hop,
177
+ path: tn.path,
178
+ via: tn.viaEdge.via ?? tn.viaEdge.type,
179
+ edgeType: tn.viaEdge.type,
180
+ state: tn.node.action,
181
+ })),
182
+ }, null, 2));
139
183
  break;
140
184
  }
141
185
  case 'csv': {
@@ -233,7 +277,12 @@ exports.blastCommand = new commander_1.Command('blast')
233
277
  }
234
278
  }
235
279
  catch (error) {
236
- console.error(chalk_1.default.red('\n❌ Error:'), error.message);
280
+ if (isJson) {
281
+ console.log(JSON.stringify({ error: error.message ?? 'Unexpected error', code: 'UNEXPECTED_ERROR' }));
282
+ }
283
+ else {
284
+ console.error(chalk_1.default.red('\n❌ Error:'), error.message);
285
+ }
237
286
  process.exit(1);
238
287
  }
239
288
  });
@@ -20,30 +20,37 @@ const display_1 = require("../utils/display");
20
20
  exports.extractCommand = new commander_1.Command('analyze')
21
21
  .description('Analyze and extract dependency graph from the current project')
22
22
  .option('-o, --output <path>', 'Output file path', 'fluent-graph.json')
23
+ .option('-f, --format <type>', 'Output format: table, json', 'table')
23
24
  .option('-q, --quiet', 'Suppress console output')
24
25
  .option('--no-display', 'Skip visual display')
25
26
  .option('--no-banner', 'Skip banner (inherited)')
26
27
  .action(async (options) => {
28
+ const isJson = options.format === 'json';
27
29
  let spinner;
28
30
  try {
29
31
  const currentWorkingDir = process.cwd();
30
32
  // Step 1: Detect ServiceNow SDK Environment
31
- if (!options.quiet) {
33
+ if (!options.quiet && !isJson) {
32
34
  spinner = (0, ora_1.default)('Detecting ServiceNow SDK...').start();
33
35
  }
34
36
  const sdkDetectionResult = await (0, detector_1.detectSDK)(currentWorkingDir);
35
37
  if (!sdkDetectionResult.found) {
36
38
  if (spinner)
37
39
  spinner.fail('SDK not found');
38
- console.error(chalk_1.default.red('\n❌ Error:'), sdkDetectionResult.error);
39
- console.log(chalk_1.default.yellow('\n💡 Make sure you\'re in a ServiceNow Fluent project directory'));
40
+ if (isJson) {
41
+ console.log(JSON.stringify({ error: sdkDetectionResult.error, code: 'SDK_NOT_FOUND' }));
42
+ }
43
+ else {
44
+ console.error(chalk_1.default.red('\n❌ Error:'), sdkDetectionResult.error);
45
+ console.log(chalk_1.default.yellow('\n💡 Make sure you\'re in a ServiceNow Fluent project directory'));
46
+ }
40
47
  process.exit(1);
41
48
  }
42
49
  if (spinner) {
43
50
  spinner.succeed(`✅ SDK detected at ${chalk_1.default.gray(sdkDetectionResult.sdkPath)}`);
44
51
  }
45
52
  // Step 2: Dynamically Load Workspace SDK
46
- if (!options.quiet) {
53
+ if (!options.quiet && !isJson) {
47
54
  spinner = (0, ora_1.default)('Loading workspace SDK...').start();
48
55
  }
49
56
  const workspaceSDK = (0, loader_1.loadWorkspaceSDK)(sdkDetectionResult.sdkPath);
@@ -51,7 +58,7 @@ exports.extractCommand = new commander_1.Command('analyze')
51
58
  spinner.succeed('Workspace SDK loaded');
52
59
  }
53
60
  // Step 3: Instantiate the Project Proxy
54
- if (!options.quiet) {
61
+ if (!options.quiet && !isJson) {
55
62
  spinner = (0, ora_1.default)('Loading project configuration...').start();
56
63
  }
57
64
  const projectInstance = new workspaceSDK.sdkapi.Project({ rootDir: currentWorkingDir });
@@ -59,10 +66,19 @@ exports.extractCommand = new commander_1.Command('analyze')
59
66
  spinner.succeed('Project loaded');
60
67
  }
61
68
  // Step 4: Extract Lineage Graph
62
- if (!options.quiet) {
69
+ if (!options.quiet && !isJson) {
63
70
  spinner = (0, ora_1.default)('Building dependency graph...').start();
64
71
  }
72
+ // In JSON mode, redirect SDK diagnostic noise (e.g. "Record defined N times")
73
+ // from stdout to stderr so stdout stays pure JSON for agent/tool consumption.
74
+ let restoreStdout;
75
+ if (isJson) {
76
+ const original = process.stdout.write.bind(process.stdout);
77
+ process.stdout.write = process.stderr.write.bind(process.stderr);
78
+ restoreStdout = () => { process.stdout.write = original; };
79
+ }
65
80
  const lineageGraph = await (0, extractor_1.extractLineageGraph)(projectInstance, workspaceSDK.registry);
81
+ restoreStdout?.();
66
82
  if (spinner) {
67
83
  spinner.succeed(`Graph built: ${chalk_1.default.cyan(lineageGraph.nodes.length)} nodes, ${chalk_1.default.cyan(lineageGraph.edges.length)} edges`);
68
84
  }
@@ -71,19 +87,29 @@ exports.extractCommand = new commander_1.Command('analyze')
71
87
  ? options.output
72
88
  : path_1.default.join(currentWorkingDir, options.output);
73
89
  (0, writer_1.writeGraph)(lineageGraph, outputFilePath);
74
- if (!options.quiet) {
75
- console.log(chalk_1.default.green('\n✅ Analysis complete'));
76
- console.log(chalk_1.default.gray(' Location: ') + chalk_1.default.white(outputFilePath));
77
- console.log(chalk_1.default.gray(' Complexity: ') + chalk_1.default.cyan((lineageGraph.edges.length / lineageGraph.nodes.length).toFixed(2)) + chalk_1.default.gray(' edges/node'));
78
- console.log(chalk_1.default.gray(' Generated at: ') + chalk_1.default.gray(new Date().toLocaleTimeString()));
90
+ if (isJson) {
91
+ // Pure JSON on stdout: the full lineage graph, ready for agent/tool consumption.
92
+ console.log(JSON.stringify(lineageGraph, null, 2));
79
93
  }
80
- // Step 6: Visual Lineage Map
81
- if (options.display && !options.quiet) {
82
- (0, display_1.displayLineageMap)(lineageGraph, workspaceSDK.registry);
94
+ else {
95
+ if (!options.quiet) {
96
+ console.log(chalk_1.default.green('\n✅ Analysis complete'));
97
+ console.log(chalk_1.default.gray(' Location: ') + chalk_1.default.white(outputFilePath));
98
+ console.log(chalk_1.default.gray(' Complexity: ') + chalk_1.default.cyan((lineageGraph.edges.length / lineageGraph.nodes.length).toFixed(2)) + chalk_1.default.gray(' edges/node'));
99
+ console.log(chalk_1.default.gray(' Generated at: ') + chalk_1.default.gray(new Date().toLocaleTimeString()));
100
+ }
101
+ // Step 6: Visual Lineage Map
102
+ if (options.display && !options.quiet) {
103
+ (0, display_1.displayLineageMap)(lineageGraph, workspaceSDK.registry);
104
+ }
83
105
  }
84
106
  }
85
107
  catch (error) {
86
- if (error instanceof Error) {
108
+ if (isJson) {
109
+ const msg = error instanceof Error ? error.message : 'Unexpected error';
110
+ console.log(JSON.stringify({ error: msg, code: 'EXTRACTION_FAILED' }));
111
+ }
112
+ else if (error instanceof Error) {
87
113
  console.error(chalk_1.default.red('\n❌ Error:'), error.message);
88
114
  if (process.env.DEBUG) {
89
115
  console.error(chalk_1.default.gray('\nStack trace:'));
package/dist/cli/index.js CHANGED
@@ -15,8 +15,21 @@ const packageJsonContent = fs_1.default.readFileSync(packageJsonPath, 'utf-8');
15
15
  const packageJson = JSON.parse(packageJsonContent);
16
16
  // ===== 2. Initialize CLI program =====
17
17
  const program = new commander_1.Command();
18
- // Show banner on first run (unless --no-banner or --quiet flag)
19
- const showBanner = !process.argv.includes('--no-banner') && !process.argv.includes('--quiet');
18
+ // Show banner on first run (unless --no-banner / --quiet, or JSON output requested).
19
+ // JSON consumers (agents, scripts) need stdout to be pure JSON, so the banner is
20
+ // suppressed whenever `--format json` (or `-f json`) is present.
21
+ const wantsJsonOutput = (() => {
22
+ const argv = process.argv;
23
+ for (let i = 0; i < argv.length; i++) {
24
+ const a = argv[i];
25
+ if (a === '--format' || a === '-f')
26
+ return argv[i + 1] === 'json';
27
+ if (a === '--format=json' || a === '-f=json')
28
+ return true;
29
+ }
30
+ return false;
31
+ })();
32
+ const showBanner = !process.argv.includes('--no-banner') && !process.argv.includes('--quiet') && !wantsJsonOutput;
20
33
  if (showBanner) {
21
34
  (0, banner_1.displayBanner)();
22
35
  }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './extractor';
2
2
  export * from './types/graphs';
3
+ export * from './blast/traversal';
package/dist/index.js CHANGED
@@ -16,3 +16,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./extractor"), exports);
18
18
  __exportStar(require("./types/graphs"), exports);
19
+ __exportStar(require("./blast/traversal"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yesprasad/fluent-graph",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Dependency visibility and impact analysis for ServiceNow Fluent SDK projects",
5
5
  "bin": {
6
6
  "fluent-graph": "./bin/fluent-graph.js"