@dataparade/cli 0.0.21 → 0.0.23

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/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataparade/cli",
3
- "version": "0.0.21",
3
+ "version": "0.0.23",
4
4
  "description": "dataPARADE CLI — scan codebases for privacy and security data flows",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -1,5 +1,5 @@
1
- import type { AiProposal, InferencePlannerResult, RunInferencePipelineInput, AiInferenceCandidate, AiProviderId, AiInferenceUsageSummary } from "./types";
2
- import type { PlatformProxyProviderConfig } from "./providers/platform-proxy-provider";
1
+ import type { AiProposal, InferencePlannerResult, RunInferencePipelineInput, AiInferenceCandidate, AiProviderId, AiInferenceUsageSummary } from './types';
2
+ import type { PlatformProxyProviderConfig } from './providers/platform-proxy-provider';
3
3
  export interface AgentOrchestratorOptions {
4
4
  provider: AiProviderId;
5
5
  model: string;
@@ -21,6 +21,12 @@ export interface AgentOrchestratorOptions {
21
21
  /** Hosted scan in VPC worker: loopback proxy → scan-cli-ai-helper Lambda. */
22
22
  hostedWorkerInferProxyUrl?: string;
23
23
  }
24
+ /**
25
+ * Hosted infer proxy rejects prompts over 512 KB, and the request body re-escapes
26
+ * the prompt JSON, so keep a margin below that.
27
+ */
28
+ export declare const MAX_PROVIDER_PROMPT_BYTES = 400000;
29
+ export declare function isPromptTooLargeError(err: unknown): boolean;
24
30
  export declare function generateAgenticProposals(input: RunInferencePipelineInput, plan: InferencePlannerResult, candidates: AiInferenceCandidate[], options: AgentOrchestratorOptions): Promise<{
25
31
  proposals: Array<{
26
32
  id: string;
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_PROVIDER_PROMPT_BYTES = void 0;
4
+ exports.isPromptTooLargeError = isPromptTooLargeError;
3
5
  exports.generateAgenticProposals = generateAgenticProposals;
4
6
  const agents_1 = require("./agents");
5
7
  const provider_prompt_1 = require("./provider-prompt");
@@ -15,6 +17,24 @@ const PROPERTY_AGENT_SLICE_SIZE = 12;
15
17
  const TP_AGENT_MAX_ROUNDS = 3;
16
18
  const TP_AGENT_MAX_FILES = 8;
17
19
  const TP_AGENT_SEARCH_LIMIT = 6;
20
+ /**
21
+ * Hosted infer proxy rejects prompts over 512 KB, and the request body re-escapes
22
+ * the prompt JSON, so keep a margin below that.
23
+ */
24
+ exports.MAX_PROVIDER_PROMPT_BYTES = 400_000;
25
+ const PROMPT_TOO_LARGE_RE = /request_body_too_large|prompt too large|prompt is too long|context_length_exceeded|maximum context length|\(413\)/i;
26
+ function promptBytes(prompt) {
27
+ return Buffer.byteLength(prompt, 'utf8');
28
+ }
29
+ function isPromptTooLargeError(err) {
30
+ const message = err instanceof Error ? err.message : String(err);
31
+ return PROMPT_TOO_LARGE_RE.test(message);
32
+ }
33
+ function warnSkippedProviderCall(agent, detail) {
34
+ if (!(0, provider_contract_1.aiDebugEnabled)())
35
+ return;
36
+ console.warn(`[dataparade-ai] ${agent} provider call skipped: ${detail}`);
37
+ }
18
38
  const IMPORT_RE = /\bimport\s+(?:[^"']+from\s+)?["']([^"']+)["']|\brequire\(["']([^"']+)["']\)/g;
19
39
  function chunkCandidates(queue, size) {
20
40
  const n = Math.max(1, Math.floor(size));
@@ -27,10 +47,10 @@ function chunkCandidates(queue, size) {
27
47
  function shouldCallProviderForAgent(agent) {
28
48
  // Flow patches are now merge-gated to intra-section changes only, so provider
29
49
  // calls can safely support both property and flow-oriented queues.
30
- return (agent === "tpAgent" ||
31
- agent === "propertyAgent" ||
32
- agent === "directionAgent" ||
33
- agent === "interactionAgent");
50
+ return (agent === 'tpAgent' ||
51
+ agent === 'propertyAgent' ||
52
+ agent === 'directionAgent' ||
53
+ agent === 'interactionAgent');
34
54
  }
35
55
  function estimateTokens(text) {
36
56
  // Rough but stable approximation used only for budget gating.
@@ -61,7 +81,7 @@ function gatherSeedPathsForCandidate(candidate, components) {
61
81
  return [];
62
82
  const out = new Set();
63
83
  const sectionId = component.properties.section_id;
64
- if (typeof sectionId === "string" && sectionId.trim())
84
+ if (typeof sectionId === 'string' && sectionId.trim())
65
85
  out.add(sectionId.trim());
66
86
  for (const loc of component.sourceLocations ?? []) {
67
87
  if (loc.filePath?.trim())
@@ -76,11 +96,18 @@ function gatherSeedPathsForCandidate(candidate, components) {
76
96
  }
77
97
  function gatherSearchTerms(componentName) {
78
98
  const base = componentName.trim().toLowerCase();
79
- const terms = new Set([base, "auth", "token", "api", "storage", "database"]);
80
- if (base.includes("supabase")) {
81
- terms.add("supabase");
82
- terms.add("storage.from");
83
- terms.add("create_client");
99
+ const terms = new Set([
100
+ base,
101
+ 'auth',
102
+ 'token',
103
+ 'api',
104
+ 'storage',
105
+ 'database',
106
+ ]);
107
+ if (base.includes('supabase')) {
108
+ terms.add('supabase');
109
+ terms.add('storage.from');
110
+ terms.add('create_client');
84
111
  }
85
112
  return [...terms].filter((t) => t.length >= 3);
86
113
  }
@@ -102,27 +129,34 @@ function pickUniqueSearchMatches(matches, alreadyReviewed, limit) {
102
129
  return [...preferred, ...fallback].slice(0, max);
103
130
  }
104
131
  function resolveRelativeImportPath(fromFile, rawImport) {
105
- if (!rawImport.startsWith("."))
132
+ if (!rawImport.startsWith('.'))
106
133
  return undefined;
107
- const normalizedFrom = fromFile.replace(/\\/g, "/");
108
- const parts = normalizedFrom.split("/");
134
+ const normalizedFrom = fromFile.replace(/\\/g, '/');
135
+ const parts = normalizedFrom.split('/');
109
136
  parts.pop();
110
- for (const piece of rawImport.split("/")) {
111
- if (piece === "." || piece === "")
137
+ for (const piece of rawImport.split('/')) {
138
+ if (piece === '.' || piece === '')
112
139
  continue;
113
- if (piece === "..")
140
+ if (piece === '..')
114
141
  parts.pop();
115
142
  else
116
143
  parts.push(piece);
117
144
  }
118
- const base = parts.join("/");
119
- const candidates = [base, `${base}.ts`, `${base}.js`, `${base}.py`, `${base}/index.ts`, `${base}/index.js`];
145
+ const base = parts.join('/');
146
+ const candidates = [
147
+ base,
148
+ `${base}.ts`,
149
+ `${base}.js`,
150
+ `${base}.py`,
151
+ `${base}/index.ts`,
152
+ `${base}/index.js`,
153
+ ];
120
154
  return candidates[0];
121
155
  }
122
156
  function expandImportPaths(filePath, content) {
123
157
  const out = [];
124
158
  for (const match of content.matchAll(IMPORT_RE)) {
125
- const rawImport = (match[1] ?? match[2] ?? "").trim();
159
+ const rawImport = (match[1] ?? match[2] ?? '').trim();
126
160
  if (!rawImport)
127
161
  continue;
128
162
  const rel = resolveRelativeImportPath(filePath, rawImport);
@@ -140,7 +174,7 @@ function logToolStep(candidateId, step) {
140
174
  const touched = step.filesTouched?.length ?? 0;
141
175
  const stats = step.stats && Object.keys(step.stats).length > 0
142
176
  ? ` stats=${JSON.stringify(step.stats)}`
143
- : "";
177
+ : '';
144
178
  console.warn(`[dataparade-ai] tpAgent tool call candidate=${candidateId} round=${step.round} action=${step.action} files_touched=${touched} detail="${step.detail}"${stats}`);
145
179
  }
146
180
  async function generateAgenticProposals(input, plan, candidates, options) {
@@ -164,6 +198,28 @@ async function generateAgenticProposals(input, plan, candidates, options) {
164
198
  model: options.model,
165
199
  apiKey: options.apiKey,
166
200
  });
201
+ const inferUnlessTooLarge = async (agent, prompt) => {
202
+ try {
203
+ return await (0, langsmith_tracing_1.traceDataparadeProviderInfer)({
204
+ providerId: options.provider,
205
+ model: options.model,
206
+ run: () => provider.infer({
207
+ prompt,
208
+ model: options.model,
209
+ endpoint: options.endpoint,
210
+ apiKey: options.apiKey,
211
+ maxTokens: options.maxTokens,
212
+ temperature: options.temperature,
213
+ }),
214
+ });
215
+ }
216
+ catch (err) {
217
+ if (!isPromptTooLargeError(err))
218
+ throw err;
219
+ warnSkippedProviderCall(agent, err instanceof Error ? err.message : String(err));
220
+ return null;
221
+ }
222
+ };
167
223
  const generated = [];
168
224
  const agenticTrace = [];
169
225
  const aggregateUsage = {
@@ -175,12 +231,12 @@ async function generateAgenticProposals(input, plan, candidates, options) {
175
231
  };
176
232
  let sequence = 0;
177
233
  for (const queue of plan.queues) {
178
- if (!skipStructural && queue.agent === "tpAgent") {
234
+ if (!skipStructural && queue.agent === 'tpAgent') {
179
235
  for (const candidate of queue.queue) {
180
236
  if (!candidate.componentId)
181
237
  continue;
182
238
  const component = input.components.find((item) => item.id === candidate.componentId);
183
- if (!component || component.type !== "third_party")
239
+ if (!component || component.type !== 'third_party')
184
240
  continue;
185
241
  const patch = (0, third_party_evidence_1.buildThirdPartyHeuristicProposal)({
186
242
  candidate,
@@ -206,7 +262,7 @@ async function generateAgenticProposals(input, plan, candidates, options) {
206
262
  if (!llmEnabled || !shouldCallProviderForAgent(queue.agent)) {
207
263
  continue;
208
264
  }
209
- if (queue.agent === "tpAgent") {
265
+ if (queue.agent === 'tpAgent') {
210
266
  const maxCalls = Math.max(0, Math.floor(queue.maxModelCalls));
211
267
  const maxCandidates = maxCalls === 0 ? 0 : Math.min(queue.queue.length, maxCalls);
212
268
  const tpCandidates = queue.queue.slice(0, maxCandidates);
@@ -226,8 +282,8 @@ async function generateAgenticProposals(input, plan, candidates, options) {
226
282
  reviewed.add(p);
227
283
  appendTraceStep(traceSteps, {
228
284
  round: 0,
229
- action: "seed_files",
230
- detail: "Seed files from detectedFrom/sourceLocations/section_id",
285
+ action: 'seed_files',
286
+ detail: 'Seed files from detectedFrom/sourceLocations/section_id',
231
287
  filesTouched: [...reviewed],
232
288
  stats: { seedCount: reviewed.size },
233
289
  });
@@ -240,7 +296,7 @@ async function generateAgenticProposals(input, plan, candidates, options) {
240
296
  reviewed.add(match.filePath);
241
297
  appendTraceStep(traceSteps, {
242
298
  round: 0,
243
- action: "search_text",
299
+ action: 'search_text',
244
300
  detail: `Search term: ${term}`,
245
301
  filesTouched: matches.map((m) => m.filePath),
246
302
  stats: { hits: matches.length },
@@ -262,29 +318,32 @@ async function generateAgenticProposals(input, plan, candidates, options) {
262
318
  preferredPaths,
263
319
  }));
264
320
  const estimatedTokens = estimateTokens(prompt) + Math.max(1, options.maxTokens ?? 8192);
265
- if (queueBudget > 0 && queueBudgetSpent + estimatedTokens > queueBudget) {
321
+ if (queueBudget > 0 &&
322
+ queueBudgetSpent + estimatedTokens > queueBudget) {
266
323
  appendTraceStep(traceSteps, {
267
324
  round,
268
- action: "provider_infer",
269
- detail: "Skipped provider inference due to queue budget limit",
325
+ action: 'provider_infer',
326
+ detail: 'Skipped provider inference due to queue budget limit',
270
327
  filesTouched: preferredPaths,
271
328
  stats: { estimatedTokens, queueBudget, queueBudgetSpent },
272
329
  });
273
330
  logToolStep(candidate.id, traceSteps[traceSteps.length - 1]);
274
331
  break;
275
332
  }
276
- const providerResult = await (0, langsmith_tracing_1.traceDataparadeProviderInfer)({
277
- providerId: options.provider,
278
- model: options.model,
279
- run: () => provider.infer({
280
- prompt,
281
- model: options.model,
282
- endpoint: options.endpoint,
283
- apiKey: options.apiKey,
284
- maxTokens: options.maxTokens,
285
- temperature: options.temperature,
286
- }),
287
- });
333
+ const providerResult = promptBytes(prompt) > exports.MAX_PROVIDER_PROMPT_BYTES
334
+ ? null
335
+ : await inferUnlessTooLarge(queue.agent, prompt);
336
+ if (!providerResult) {
337
+ appendTraceStep(traceSteps, {
338
+ round,
339
+ action: 'provider_infer',
340
+ detail: 'Skipped provider inference because the prompt is too large',
341
+ filesTouched: preferredPaths,
342
+ stats: { promptBytes: promptBytes(prompt) },
343
+ });
344
+ logToolStep(candidate.id, traceSteps[traceSteps.length - 1]);
345
+ break;
346
+ }
288
347
  if (queueBudget > 0)
289
348
  queueBudgetSpent += estimatedTokens;
290
349
  if (providerResult.usage) {
@@ -292,9 +351,10 @@ async function generateAgenticProposals(input, plan, candidates, options) {
292
351
  aggregateUsage.inputTokens += providerResult.usage.inputTokens;
293
352
  aggregateUsage.outputTokens += providerResult.usage.outputTokens;
294
353
  aggregateUsage.totalTokens += providerResult.usage.totalTokens;
295
- if (typeof providerResult.usage.estimatedCostUsd === "number") {
354
+ if (typeof providerResult.usage.estimatedCostUsd === 'number') {
296
355
  aggregateUsage.estimatedCostUsd =
297
- (aggregateUsage.estimatedCostUsd ?? 0) + providerResult.usage.estimatedCostUsd;
356
+ (aggregateUsage.estimatedCostUsd ?? 0) +
357
+ providerResult.usage.estimatedCostUsd;
298
358
  }
299
359
  else {
300
360
  aggregateUsage.estimatedCostUsd = undefined;
@@ -302,10 +362,13 @@ async function generateAgenticProposals(input, plan, candidates, options) {
302
362
  }
303
363
  appendTraceStep(traceSteps, {
304
364
  round,
305
- action: "provider_infer",
306
- detail: "Provider inference call for current reviewed file set",
365
+ action: 'provider_infer',
366
+ detail: 'Provider inference call for current reviewed file set',
307
367
  filesTouched: preferredPaths,
308
- stats: { reviewedCount: preferredPaths.length, proposals: providerResult.proposals.length },
368
+ stats: {
369
+ reviewedCount: preferredPaths.length,
370
+ proposals: providerResult.proposals.length,
371
+ },
309
372
  });
310
373
  logToolStep(candidate.id, traceSteps[traceSteps.length - 1]);
311
374
  const acceptedThisRound = [];
@@ -331,7 +394,9 @@ async function generateAgenticProposals(input, plan, candidates, options) {
331
394
  const beforeExpand = reviewed.size;
332
395
  const filesForExpand = [...reviewed].slice(0, maxFiles);
333
396
  for (const fp of filesForExpand) {
334
- const fi = input.files ? (0, scan_paths_1.resolveScannedFileExact)(input.files, fp) : undefined;
397
+ const fi = input.files
398
+ ? (0, scan_paths_1.resolveScannedFileExact)(input.files, fp)
399
+ : undefined;
335
400
  if (!fi)
336
401
  continue;
337
402
  const imports = expandImportPaths(fi.path, fi.content);
@@ -350,8 +415,8 @@ async function generateAgenticProposals(input, plan, candidates, options) {
350
415
  const added = reviewed.size - beforeExpand;
351
416
  appendTraceStep(traceSteps, {
352
417
  round,
353
- action: "expand_imports",
354
- detail: "Expand import graph from reviewed files",
418
+ action: 'expand_imports',
419
+ detail: 'Expand import graph from reviewed files',
355
420
  filesTouched: [...reviewed],
356
421
  stats: { addedFiles: added, totalReviewed: reviewed.size },
357
422
  });
@@ -361,8 +426,8 @@ async function generateAgenticProposals(input, plan, candidates, options) {
361
426
  }
362
427
  appendTraceStep(traceSteps, {
363
428
  round: executedRounds,
364
- action: "finalize",
365
- detail: "Finalize accepted proposals for candidate",
429
+ action: 'finalize',
430
+ detail: 'Finalize accepted proposals for candidate',
366
431
  filesTouched: [...reviewed],
367
432
  stats: { finalProposalCount: finalProposals.length },
368
433
  });
@@ -386,8 +451,10 @@ async function generateAgenticProposals(input, plan, candidates, options) {
386
451
  continue;
387
452
  }
388
453
  // Non-tp agents stay in bounded prompt batches.
389
- const providerSlices = chunkCandidates(queue.queue, PROPERTY_AGENT_SLICE_SIZE);
390
- const preparedProviderCalls = providerSlices.map((slice) => {
454
+ const pendingSlices = chunkCandidates(queue.queue, PROPERTY_AGENT_SLICE_SIZE);
455
+ const preparedProviderCalls = [];
456
+ while (pendingSlices.length > 0) {
457
+ const slice = pendingSlices.shift();
391
458
  const prompt = JSON.stringify((0, provider_prompt_1.buildProviderPromptPayload)({
392
459
  agent: queue.agent,
393
460
  queue: slice,
@@ -396,9 +463,20 @@ async function generateAgenticProposals(input, plan, candidates, options) {
396
463
  sections: input.sections,
397
464
  files: input.files,
398
465
  }));
466
+ const bytes = promptBytes(prompt);
467
+ if (bytes > exports.MAX_PROVIDER_PROMPT_BYTES) {
468
+ if (slice.length > 1) {
469
+ const mid = Math.ceil(slice.length / 2);
470
+ pendingSlices.unshift(slice.slice(0, mid), slice.slice(mid));
471
+ }
472
+ else {
473
+ warnSkippedProviderCall(queue.agent, `prompt for ${slice[0].id} is ${bytes} bytes (limit ${exports.MAX_PROVIDER_PROMPT_BYTES})`);
474
+ }
475
+ continue;
476
+ }
399
477
  const estimatedTokens = estimateTokens(prompt) + Math.max(1, options.maxTokens ?? 8192);
400
- return { prompt, estimatedTokens };
401
- });
478
+ preparedProviderCalls.push({ prompt, estimatedTokens });
479
+ }
402
480
  const maxCalls = Math.max(0, Math.floor(queue.maxModelCalls));
403
481
  const callsWithinLimit = maxCalls === 0
404
482
  ? []
@@ -414,7 +492,7 @@ async function generateAgenticProposals(input, plan, candidates, options) {
414
492
  spent += call.estimatedTokens;
415
493
  }
416
494
  // Avoid starving property enrichment when estimated tokens are conservative.
417
- if (queue.agent === "propertyAgent" &&
495
+ if (queue.agent === 'propertyAgent' &&
418
496
  budgetedCalls.length === 0 &&
419
497
  callsWithinLimit.length > 0) {
420
498
  budgetedCalls.push(callsWithinLimit[0]);
@@ -425,27 +503,19 @@ async function generateAgenticProposals(input, plan, candidates, options) {
425
503
  budgetedCalls.push(...[]);
426
504
  }
427
505
  const providerConcurrency = Math.max(1, Math.floor(options.providerConcurrency ?? 1));
428
- const providerResults = await mapWithConcurrency(budgetedCalls, providerConcurrency, (call) => (0, langsmith_tracing_1.traceDataparadeProviderInfer)({
429
- providerId: options.provider,
430
- model: options.model,
431
- run: () => provider.infer({
432
- prompt: call.prompt,
433
- model: options.model,
434
- endpoint: options.endpoint,
435
- apiKey: options.apiKey,
436
- maxTokens: options.maxTokens,
437
- temperature: options.temperature,
438
- }),
439
- }));
506
+ const providerResults = await mapWithConcurrency(budgetedCalls, providerConcurrency, (call) => inferUnlessTooLarge(queue.agent, call.prompt));
440
507
  for (const providerResult of providerResults) {
508
+ if (!providerResult)
509
+ continue;
441
510
  if (providerResult.usage) {
442
511
  aggregateUsage.providerCalls += 1;
443
512
  aggregateUsage.inputTokens += providerResult.usage.inputTokens;
444
513
  aggregateUsage.outputTokens += providerResult.usage.outputTokens;
445
514
  aggregateUsage.totalTokens += providerResult.usage.totalTokens;
446
- if (typeof providerResult.usage.estimatedCostUsd === "number") {
515
+ if (typeof providerResult.usage.estimatedCostUsd === 'number') {
447
516
  aggregateUsage.estimatedCostUsd =
448
- (aggregateUsage.estimatedCostUsd ?? 0) + providerResult.usage.estimatedCostUsd;
517
+ (aggregateUsage.estimatedCostUsd ?? 0) +
518
+ providerResult.usage.estimatedCostUsd;
449
519
  }
450
520
  else {
451
521
  aggregateUsage.estimatedCostUsd = undefined;
@@ -14,12 +14,44 @@ const MAX_SOURCE_LOCS = 12;
14
14
  const MAX_FILES_IN_PROMPT = 28;
15
15
  const MAX_CHARS_PER_FILE = 14_000;
16
16
  const MAX_TOTAL_EXCERPT_CHARS = 100_000;
17
- const NON_ENRICHMENT_PROPERTY_KEYS = new Set(['inference_status']);
17
+ /** Cap per already-set property value; scanner evidence lists can reach hundreds of KB. */
18
+ const MAX_PROPERTY_VALUE_CHARS = 4_000;
19
+ const NON_ENRICHMENT_PROPERTY_KEYS = new Set([
20
+ 'inference_status',
21
+ 'propertyEvidence',
22
+ ]);
18
23
  function truncateChars(text, max) {
19
24
  if (text.length <= max)
20
25
  return text;
21
26
  return `${text.slice(0, max)}\n\n...[truncated]`;
22
27
  }
28
+ function compactDataActions(value) {
29
+ if (!Array.isArray(value))
30
+ return value;
31
+ const actions = value.map((entry) => entry && typeof entry === 'object' && 'action' in entry
32
+ ? entry.action
33
+ : entry);
34
+ return [...new Set(actions)];
35
+ }
36
+ function capPropertyValue(value) {
37
+ if (JSON.stringify(value).length <= MAX_PROPERTY_VALUE_CHARS)
38
+ return value;
39
+ if (typeof value === 'string') {
40
+ return truncateChars(value, MAX_PROPERTY_VALUE_CHARS);
41
+ }
42
+ if (Array.isArray(value)) {
43
+ const kept = [];
44
+ let size = 2;
45
+ for (const item of value) {
46
+ size += JSON.stringify(item).length + 1;
47
+ if (size > MAX_PROPERTY_VALUE_CHARS)
48
+ break;
49
+ kept.push(item);
50
+ }
51
+ return kept;
52
+ }
53
+ return undefined;
54
+ }
23
55
  function pathsFromComponent(comp) {
24
56
  if (!comp)
25
57
  return [];
@@ -127,7 +159,9 @@ function slimComponentForLlm(component) {
127
159
  sparseKeys.push(key);
128
160
  }
129
161
  else {
130
- propertiesSet[key] = value;
162
+ const compact = capPropertyValue(key === 'dataActions' ? compactDataActions(value) : value);
163
+ if (compact !== undefined)
164
+ propertiesSet[key] = compact;
131
165
  }
132
166
  }
133
167
  const prioritizedSparseKeys = (0, property_priority_1.sortPropertyKeysByPriority)(sparseKeys);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * NestJS `services/*.service.ts` classes and bare HTTP clients (Axios, HttpClient)
3
+ * are implementation details. Directus collection services (`extends ItemsService`)
4
+ * and calls that name a real third party stay on the diagram.
5
+ */
6
+ export interface OmittableLocation {
7
+ filePath: string;
8
+ code?: string;
9
+ startLine?: number;
10
+ }
11
+ export interface OmittableComponent {
12
+ id: string;
13
+ name: string;
14
+ type: string;
15
+ subType?: string;
16
+ detectedFrom?: Array<{
17
+ pattern: string;
18
+ sourceLocation?: OmittableLocation;
19
+ }>;
20
+ sourceLocations?: OmittableLocation[];
21
+ properties?: Record<string, unknown>;
22
+ }
23
+ export interface OmittableFlow {
24
+ sourceComponentId: string;
25
+ targetComponentId: string;
26
+ type: string;
27
+ }
28
+ export interface OmitInternalImplementationOptions {
29
+ readSource?: (filePath: string) => string | undefined;
30
+ }
31
+ export declare function omitInternalImplementationNodes<C extends OmittableComponent, F extends OmittableFlow>(components: C[], flows: F[], options?: OmitInternalImplementationOptions): {
32
+ components: C[];
33
+ dataFlows: F[];
34
+ };
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ /**
3
+ * NestJS `services/*.service.ts` classes and bare HTTP clients (Axios, HttpClient)
4
+ * are implementation details. Directus collection services (`extends ItemsService`)
5
+ * and calls that name a real third party stay on the diagram.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.omitInternalImplementationNodes = omitInternalImplementationNodes;
9
+ const HTTP_TRANSPORT_NAMES = new Set([
10
+ 'axios',
11
+ 'fetch',
12
+ 'got',
13
+ 'ky',
14
+ 'httpclient',
15
+ 'httpclientfactory',
16
+ 'restsharp',
17
+ 'flurl',
18
+ 'undici',
19
+ 'nodefetch',
20
+ 'crossfetch',
21
+ ]);
22
+ function compactName(value) {
23
+ return value.trim().toLowerCase().replace(/[\s_-]+/g, '');
24
+ }
25
+ function isMainApplication(component) {
26
+ const flag = component.properties?.isMainApplication;
27
+ return flag === true || flag === 'true';
28
+ }
29
+ function sectionId(component) {
30
+ const raw = component.properties?.section_id;
31
+ return typeof raw === 'string' ? raw.trim() : '';
32
+ }
33
+ function serviceFileLocations(component) {
34
+ return (component.sourceLocations ?? []).filter((location) => /(?:^|\/)services\/.+\.tsx?$/i.test(location.filePath.replace(/\\/g, '/')));
35
+ }
36
+ function declarationWindow(source, startLine) {
37
+ const lines = source.split(/\r?\n/);
38
+ const start = Math.max(0, (startLine ?? 1) - 1);
39
+ return lines.slice(start, start + 4).join('\n');
40
+ }
41
+ function isDirectusItemsService(component, readSource) {
42
+ for (const location of serviceFileLocations(component)) {
43
+ const fromSnippet = location.code ?? '';
44
+ if (/extends\s+(?:\w+\.)?ItemsService\b/.test(fromSnippet))
45
+ return true;
46
+ const source = readSource(location.filePath);
47
+ if (!source)
48
+ continue;
49
+ if (/extends\s+(?:\w+\.)?ItemsService\b/.test(declarationWindow(source, location.startLine))) {
50
+ return true;
51
+ }
52
+ }
53
+ return false;
54
+ }
55
+ function isNestServiceClassNode(component, readSource) {
56
+ if (component.type !== 'asset' || component.subType !== 'service')
57
+ return false;
58
+ const locations = serviceFileLocations(component);
59
+ if (locations.length === 0)
60
+ return false;
61
+ const patterns = (component.detectedFrom ?? []).map((ref) => ref.pattern);
62
+ if (patterns.length === 0 || patterns.some((pattern) => pattern !== 'auth_middleware')) {
63
+ return false;
64
+ }
65
+ if (isDirectusItemsService(component, readSource))
66
+ return false;
67
+ for (const location of locations) {
68
+ const snippet = location.code ?? '';
69
+ if (/export\s+class\s+\w+Service\b/.test(snippet))
70
+ return true;
71
+ const source = readSource(location.filePath);
72
+ if (!source)
73
+ continue;
74
+ if (/export\s+class\s+\w+Service\b/.test(declarationWindow(source, location.startLine))) {
75
+ return true;
76
+ }
77
+ }
78
+ return false;
79
+ }
80
+ function stringProp(component, key) {
81
+ const value = component.properties?.[key];
82
+ return typeof value === 'string' ? value : '';
83
+ }
84
+ function hasPublicUrl(component) {
85
+ const url = stringProp(component, 'url') || (/^https?:\/\//i.test(component.name) ? component.name : '');
86
+ if (!/^https?:\/\//i.test(url))
87
+ return false;
88
+ if (/\$\{|process\.env|localhost|127\.0\.0\.1/i.test(url))
89
+ return false;
90
+ return true;
91
+ }
92
+ function isBareHttpTransportNode(component) {
93
+ if (component.properties?.sourceContext === 'dependency_manifest')
94
+ return false;
95
+ if (hasPublicUrl(component))
96
+ return false;
97
+ const serviceName = compactName(stringProp(component, 'serviceName'));
98
+ if (serviceName && !HTTP_TRANSPORT_NAMES.has(serviceName))
99
+ return false;
100
+ const client = compactName(stringProp(component, 'client'));
101
+ const fromName = compactName(component.name).replace(/call$/, '');
102
+ const namedAsClientCall = /\bcall$/i.test(component.name.trim()) &&
103
+ HTTP_TRANSPORT_NAMES.has(fromName);
104
+ return (HTTP_TRANSPORT_NAMES.has(client) ||
105
+ HTTP_TRANSPORT_NAMES.has(serviceName) ||
106
+ namedAsClientCall);
107
+ }
108
+ function hubIdFor(components, dropped, dropIds) {
109
+ const hubs = components.filter((component) => isMainApplication(component) && !dropIds.has(component.id));
110
+ const section = sectionId(dropped);
111
+ const sameSection = hubs.find((hub) => sectionId(hub) === section);
112
+ return (sameSection ?? hubs[0])?.id;
113
+ }
114
+ function omitInternalImplementationNodes(components, flows, options = {}) {
115
+ const readSource = options.readSource ?? (() => undefined);
116
+ const dropIds = new Set(components
117
+ .filter((component) => isNestServiceClassNode(component, readSource) ||
118
+ isBareHttpTransportNode(component))
119
+ .map((component) => component.id));
120
+ if (dropIds.size === 0) {
121
+ return { components, dataFlows: flows };
122
+ }
123
+ const kept = components.filter((component) => !dropIds.has(component.id));
124
+ const seen = new Set();
125
+ const dataFlows = [];
126
+ for (const flow of flows) {
127
+ if (dropIds.has(flow.targetComponentId))
128
+ continue;
129
+ let sourceId = flow.sourceComponentId;
130
+ if (dropIds.has(sourceId)) {
131
+ const dropped = components.find((component) => component.id === sourceId);
132
+ const hub = dropped ? hubIdFor(components, dropped, dropIds) : undefined;
133
+ if (!hub || hub === flow.targetComponentId)
134
+ continue;
135
+ sourceId = hub;
136
+ }
137
+ const key = `${sourceId}\t${flow.targetComponentId}\t${flow.type}`;
138
+ if (seen.has(key))
139
+ continue;
140
+ seen.add(key);
141
+ dataFlows.push(sourceId === flow.sourceComponentId
142
+ ? flow
143
+ : { ...flow, sourceComponentId: sourceId });
144
+ }
145
+ return { components: kept, dataFlows };
146
+ }