@dataparade/cli 0.0.26 → 0.0.29

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 (120) hide show
  1. package/README.md +56 -13
  2. package/dist/package.json +7 -7
  3. package/dist/src/ai-enrichment/providers/platform-proxy-provider.js +0 -1
  4. package/dist/src/cli.d.ts +3 -0
  5. package/dist/src/cli.js +102 -68
  6. package/dist/src/discoveries/contract/ocsf-discovery-record.d.ts +1 -1
  7. package/dist/src/discoveries/load-ocsf-discoveries.d.ts +0 -8
  8. package/dist/src/discoveries/load-ocsf-discoveries.js +0 -31
  9. package/dist/src/discoveries/write-ocsf-discoveries.d.ts +0 -8
  10. package/dist/src/discoveries/write-ocsf-discoveries.js +0 -38
  11. package/dist/src/evals/run-model-matrix.js +0 -1
  12. package/dist/src/export/export-ocsf.d.ts +18 -0
  13. package/dist/src/export/export-ocsf.js +104 -0
  14. package/dist/src/export/register-export-commands.d.ts +2 -0
  15. package/dist/src/export/register-export-commands.js +30 -0
  16. package/dist/src/facts/apply-answers.d.ts +29 -0
  17. package/dist/src/facts/apply-answers.js +202 -0
  18. package/dist/src/facts/build-facts.d.ts +24 -0
  19. package/dist/src/facts/build-facts.js +198 -0
  20. package/dist/src/facts/io.d.ts +17 -0
  21. package/dist/src/facts/io.js +67 -0
  22. package/dist/src/facts/layout.d.ts +29 -0
  23. package/dist/src/facts/layout.js +38 -0
  24. package/dist/src/facts/schema.d.ts +265 -0
  25. package/dist/src/facts/schema.js +122 -0
  26. package/dist/src/facts/slug.d.ts +7 -0
  27. package/dist/src/facts/slug.js +47 -0
  28. package/dist/src/kb/brief.d.ts +1 -2
  29. package/dist/src/kb/brief.js +2 -4
  30. package/dist/src/kb/interview-record.d.ts +18 -0
  31. package/dist/src/kb/interview-record.js +70 -0
  32. package/dist/src/kb/kb-store.d.ts +24 -18
  33. package/dist/src/kb/kb-store.js +89 -28
  34. package/dist/src/kb/land.d.ts +32 -12
  35. package/dist/src/kb/land.js +97 -90
  36. package/dist/src/kb/migrate.d.ts +23 -0
  37. package/dist/src/kb/migrate.js +91 -0
  38. package/dist/src/kb/project-diagram.js +4 -4
  39. package/dist/src/kb/register-kb-commands.js +71 -20
  40. package/dist/src/observability/scan-sentry.js +0 -1
  41. package/dist/src/output/scan-output-excludes.d.ts +1 -1
  42. package/dist/src/output/scan-output-excludes.js +14 -5
  43. package/dist/src/output/write-scan-knowledge.d.ts +33 -0
  44. package/dist/src/output/write-scan-knowledge.js +115 -0
  45. package/dist/src/platform-api/estimate-scan-footprint.d.ts +31 -0
  46. package/dist/src/platform-api/estimate-scan-footprint.js +75 -2
  47. package/dist/src/platform-api/fetch-failure.d.ts +5 -0
  48. package/dist/src/platform-api/fetch-failure.js +13 -0
  49. package/dist/src/platform-api/upload-client.d.ts +5 -0
  50. package/dist/src/platform-api/upload-client.js +11 -1
  51. package/dist/src/ui/scan-progress-renderer.d.ts +16 -0
  52. package/dist/src/ui/scan-progress-renderer.js +29 -3
  53. package/dist/src/ui/teaching-lines.js +18 -6
  54. package/dist/src/upload/collect-scan-sidecars.d.ts +2 -27
  55. package/dist/src/upload/collect-scan-sidecars.js +25 -121
  56. package/dist/src/upload/run-upload.js +0 -3
  57. package/dist/tests/cli/cli.spec.js +30 -13
  58. package/dist/tests/helpers/facts-fixture.d.ts +9 -0
  59. package/dist/tests/helpers/facts-fixture.js +72 -0
  60. package/dist/tests/unit/cli/scan-ai-session-fallback.spec.js +156 -0
  61. package/dist/tests/unit/export/export-ocsf.spec.js +72 -0
  62. package/dist/tests/unit/facts/apply-answers.spec.d.ts +1 -0
  63. package/dist/tests/unit/facts/apply-answers.spec.js +128 -0
  64. package/dist/tests/unit/facts/build-facts.spec.d.ts +1 -0
  65. package/dist/tests/unit/facts/build-facts.spec.js +161 -0
  66. package/dist/tests/unit/facts/slug.spec.d.ts +1 -0
  67. package/dist/tests/unit/facts/slug.spec.js +30 -0
  68. package/dist/tests/unit/kb/kb-interview-loop.spec.js +83 -35
  69. package/dist/tests/unit/kb/migrate.spec.d.ts +1 -0
  70. package/dist/tests/unit/kb/migrate.spec.js +108 -0
  71. package/dist/tests/unit/output/graphify-cache-dir.spec.d.ts +1 -0
  72. package/dist/tests/unit/output/graphify-cache-dir.spec.js +20 -0
  73. package/dist/tests/unit/output/scan-output-excludes.spec.js +4 -2
  74. package/dist/tests/unit/platform-api/estimate-scan-footprint.spec.js +77 -0
  75. package/dist/tests/unit/platform-api/upload-client.spec.js +2 -2
  76. package/dist/tests/unit/ui/scan-progress-renderer.spec.js +21 -0
  77. package/dist/tests/unit/ui/teaching-lines.spec.js +16 -0
  78. package/dist/tests/unit/upload/collect-scan-sidecars.spec.js +46 -46
  79. package/dist/tests/unit/upload/pack-scan-upload.spec.js +6 -6
  80. package/dist/vendor/scanner/dist/src/classifier/component-factory.js +6 -14
  81. package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.d.ts +1 -0
  82. package/dist/vendor/scanner/dist/src/classifier/external-url-third-party.js +32 -1
  83. package/dist/vendor/scanner/dist/src/classifier/naming.d.ts +5 -0
  84. package/dist/vendor/scanner/dist/src/classifier/naming.js +8 -4
  85. package/dist/vendor/scanner/dist/src/core/pipeline/build-scan-personal-data-layers.js +26 -14
  86. package/dist/vendor/scanner/dist/src/core/pipeline/enrich-personal-data-layers.js +3 -1
  87. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.d.ts +18 -0
  88. package/dist/vendor/scanner/dist/src/data-flow/intra-component-lineage.js +125 -66
  89. package/dist/vendor/scanner/dist/src/index.d.ts +2 -0
  90. package/dist/vendor/scanner/dist/src/index.js +7 -2
  91. package/dist/vendor/scanner/dist/src/ingest/file-system.d.ts +5 -0
  92. package/dist/vendor/scanner/dist/src/ingest/file-system.js +5 -0
  93. package/dist/vendor/scanner/dist/src/ingest/gitignore.d.ts +17 -0
  94. package/dist/vendor/scanner/dist/src/ingest/gitignore.js +47 -9
  95. package/dist/vendor/scanner/dist/src/ingest/schema-files.d.ts +10 -2
  96. package/dist/vendor/scanner/dist/src/ingest/schema-files.js +24 -7
  97. package/dist/vendor/scanner/dist/src/patterns/frontend-frameworks.d.ts +3 -0
  98. package/dist/vendor/scanner/dist/src/patterns/frontend-frameworks.js +45 -0
  99. package/dist/vendor/scanner/dist/src/patterns/scan-exclusions.js +7 -0
  100. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.d.ts +24 -0
  101. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.js +19 -6
  102. package/dist/vendor/scanner/dist/src/pii-signals/occurrence-group.js +5 -2
  103. package/dist/vendor/scanner/dist/src/pii-signals/pii-signal-aliases.js +5 -2
  104. package/dist/vendor/scanner/patterns/classifier/third-party.classifier.yaml +8 -0
  105. package/dist/vendor/scanner/patterns/third-party.patterns.yaml +9 -0
  106. package/package.json +7 -7
  107. package/dist/src/discoveries/project-collected-diagram.d.ts +0 -7
  108. package/dist/src/discoveries/project-collected-diagram.js +0 -182
  109. package/dist/src/discoveries/project-ocsf-to-discoveries-document.d.ts +0 -16
  110. package/dist/src/discoveries/project-ocsf-to-discoveries-document.js +0 -269
  111. package/dist/src/discoveries/scan-result-to-discovery-input.d.ts +0 -13
  112. package/dist/src/discoveries/scan-result-to-discovery-input.js +0 -60
  113. package/dist/src/output/write-knowledge-graph.d.ts +0 -20
  114. package/dist/src/output/write-knowledge-graph.js +0 -53
  115. package/dist/src/output/write-scan-discoveries.d.ts +0 -17
  116. package/dist/src/output/write-scan-discoveries.js +0 -61
  117. package/dist/tests/unit/discoveries/project-collected-diagram.spec.js +0 -97
  118. package/dist/tests/unit/discoveries/rescan-replaces-scan-records.spec.js +0 -89
  119. /package/dist/tests/unit/{discoveries/project-collected-diagram.spec.d.ts → cli/scan-ai-session-fallback.spec.d.ts} +0 -0
  120. /package/dist/tests/unit/{discoveries/rescan-replaces-scan-records.spec.d.ts → export/export-ocsf.spec.d.ts} +0 -0
@@ -7,6 +7,7 @@ const flow_source_patterns_1 = require("../patterns/flow-source-patterns");
7
7
  const terraform_utility_resource_1 = require("../analyzers/terraform/terraform-utility-resource");
8
8
  const property_evidence_1 = require("./property-evidence");
9
9
  const frontend_frameworks_1 = require("../patterns/frontend-frameworks");
10
+ const naming_1 = require("./naming");
10
11
  const MERGED_HTTP_ROUTE_GROUP_KEY_PREFIX = "__cli_http_api_routes__";
11
12
  const FRONTEND_FRAMEWORK_GROUP_KEY_PREFIX = "__cli_frontend_framework__";
12
13
  const MERGED_HTTP_ROUTE_DISPLAY_NAME = "HTTP API";
@@ -48,15 +49,6 @@ function getSectionIdFromProperties(properties) {
48
49
  return raw.trim();
49
50
  return "<unsectioned>";
50
51
  }
51
- function toDisplayName(normalized, fallback) {
52
- const base = normalized || fallback.trim();
53
- if (!base)
54
- return "<unknown>";
55
- return base
56
- .split(/\s+/)
57
- .map((part) => part.length === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1))
58
- .join(" ");
59
- }
60
52
  function normalizeApiDisplayName(rawName, properties) {
61
53
  const name = (rawName || "").trim();
62
54
  if (!name)
@@ -120,7 +112,7 @@ function terraformInfrastructureDisplayName(finding, config) {
120
112
  return `${bn.trim()} (${rt.trim()})`;
121
113
  }
122
114
  const normalized = normalizeComponentName(finding.name, config.nameNormalization);
123
- return toDisplayName(normalized, finding.name);
115
+ return (0, naming_1.toDisplayName)(normalized, finding.name);
124
116
  }
125
117
  function groupFindings(findings, config) {
126
118
  const groups = new Map();
@@ -137,10 +129,10 @@ function groupFindings(findings, config) {
137
129
  : "frontend";
138
130
  const packageNameRaw = finding.properties?.packageName;
139
131
  const packageDisplayName = typeof packageNameRaw === "string" && packageNameRaw.trim()
140
- ? toDisplayName(normalizeComponentName(packageNameRaw, config.nameNormalization), packageNameRaw)
132
+ ? (0, naming_1.toDisplayName)(normalizeComponentName(packageNameRaw, config.nameNormalization), packageNameRaw)
141
133
  : undefined;
142
134
  key = `${FRONTEND_FRAMEWORK_GROUP_KEY_PREFIX}:${sectionId}:${framework}`;
143
- displayName = packageDisplayName ?? toDisplayName(framework, framework);
135
+ displayName = packageDisplayName ?? (0, naming_1.toDisplayName)(framework, framework);
144
136
  }
145
137
  else {
146
138
  const sectionId = getSectionIdFromProperties(finding.properties);
@@ -192,7 +184,7 @@ function groupFindings(findings, config) {
192
184
  .replace(/\\/g, "/")
193
185
  .toLowerCase();
194
186
  key = `${sectionId}::${keyBase}::${filePath}`;
195
- displayName = toDisplayName(keyBase, keyBase);
187
+ displayName = (0, naming_1.toDisplayName)(keyBase, keyBase);
196
188
  }
197
189
  let group = groups.get(key);
198
190
  if (!group) {
@@ -527,7 +519,7 @@ function classifyRawFindings(rawFindings, options) {
527
519
  const svc = mergedProperties.serviceName;
528
520
  if (typeof svc === "string" && svc.trim()) {
529
521
  const normalizedService = normalizeComponentName(svc, config.nameNormalization);
530
- component.name = toDisplayName(normalizedService, svc);
522
+ component.name = (0, naming_1.toDisplayName)(normalizedService, svc);
531
523
  }
532
524
  }
533
525
  if (component.type === "asset" && component.subType === "api") {
@@ -8,6 +8,7 @@ export declare function hostMatchesOrganizationDomains(hostname: string, organiz
8
8
  export declare function urlMatchesOrganizationDomains(url: string, organizationDomains: readonly string[]): boolean;
9
9
  export declare function externalApiCallFindingUrl(finding: RawFinding): string | undefined;
10
10
  export declare function isOrganizationOwnedExternalApiFinding(finding: RawFinding, organizationDomains: readonly string[]): boolean;
11
+ export declare function isReservedPlaceholderHost(hostname: string): boolean;
11
12
  export declare function shouldIgnoreExternalHttpUrl(url: string | undefined, options?: ExternalHttpUrlOptions): boolean;
12
13
  /**
13
14
  * Stable third-party key: registrable-style host (last two DNS labels), e.g.
@@ -5,6 +5,7 @@ exports.hostMatchesOrganizationDomains = hostMatchesOrganizationDomains;
5
5
  exports.urlMatchesOrganizationDomains = urlMatchesOrganizationDomains;
6
6
  exports.externalApiCallFindingUrl = externalApiCallFindingUrl;
7
7
  exports.isOrganizationOwnedExternalApiFinding = isOrganizationOwnedExternalApiFinding;
8
+ exports.isReservedPlaceholderHost = isReservedPlaceholderHost;
8
9
  exports.shouldIgnoreExternalHttpUrl = shouldIgnoreExternalHttpUrl;
9
10
  exports.deriveServiceKeyFromHostname = deriveServiceKeyFromHostname;
10
11
  exports.urlHostMatchKeys = urlHostMatchKeys;
@@ -123,6 +124,34 @@ function isLocalOrPrivateHost(hostname) {
123
124
  }
124
125
  return false;
125
126
  }
127
+ /**
128
+ * RFC 2606 / RFC 6761 reserved names: example.com/.org/.net (and subdomains) plus
129
+ * the .test, .example, .invalid and .localhost TLDs. These are documentation
130
+ * placeholders, never real vendors.
131
+ */
132
+ const RESERVED_PLACEHOLDER_DOMAINS = [
133
+ "example.com",
134
+ "example.org",
135
+ "example.net",
136
+ ];
137
+ const RESERVED_PLACEHOLDER_TLDS = [
138
+ "test",
139
+ "example",
140
+ "invalid",
141
+ "localhost",
142
+ ];
143
+ function isReservedPlaceholderHost(hostname) {
144
+ const h = hostname.toLowerCase().replace(/\.$/, "");
145
+ if (!h)
146
+ return false;
147
+ for (const d of RESERVED_PLACEHOLDER_DOMAINS) {
148
+ if (h === d || h.endsWith(`.${d}`))
149
+ return true;
150
+ }
151
+ const labels = h.split(".");
152
+ const tld = labels[labels.length - 1] ?? "";
153
+ return RESERVED_PLACEHOLDER_TLDS.includes(tld);
154
+ }
126
155
  function shouldIgnoreExternalHttpUrl(url, options) {
127
156
  if (typeof url !== "string")
128
157
  return true;
@@ -144,6 +173,8 @@ function shouldIgnoreExternalHttpUrl(url, options) {
144
173
  }
145
174
  if (isLocalOrPrivateHost(hostname))
146
175
  return true;
176
+ if (isReservedPlaceholderHost(hostname))
177
+ return true;
147
178
  const organizationDomains = resolveOrganizationDomains(options);
148
179
  if (hostMatchesOrganizationDomains(hostname, organizationDomains)) {
149
180
  return true;
@@ -260,7 +291,7 @@ function inferThirdPartyFromLiteralHttpUrl(finding, options) {
260
291
  catch {
261
292
  return undefined;
262
293
  }
263
- if (isLocalOrPrivateHost(hostname)) {
294
+ if (isLocalOrPrivateHost(hostname) || isReservedPlaceholderHost(hostname)) {
264
295
  return undefined;
265
296
  }
266
297
  const serviceName = deriveServiceKeyFromHostname(hostname);
@@ -1,4 +1,9 @@
1
1
  import type { NameNormalizationConfig } from "./config";
2
2
  export declare function normalizeComponentName(rawName: string, rules: NameNormalizationConfig): string;
3
+ /**
4
+ * Human-readable display name: underscores (snake_case ids such as
5
+ * `google_identity`) and whitespace separate words, and each word is capitalized.
6
+ * Dots and hyphens inside a word are preserved (`notion.so`, `next-auth`).
7
+ */
3
8
  export declare function toDisplayName(normalized: string, fallback: string): string;
4
9
  export declare function normalizeApiDisplayName(rawName: string, properties: Record<string, unknown> | undefined): string;
@@ -41,15 +41,19 @@ function normalizeComponentName(rawName, rules) {
41
41
  }
42
42
  return lower;
43
43
  }
44
+ /**
45
+ * Human-readable display name: underscores (snake_case ids such as
46
+ * `google_identity`) and whitespace separate words, and each word is capitalized.
47
+ * Dots and hyphens inside a word are preserved (`notion.so`, `next-auth`).
48
+ */
44
49
  function toDisplayName(normalized, fallback) {
45
50
  const base = normalized || fallback.trim();
46
51
  if (!base)
47
52
  return "<unknown>";
48
53
  return base
49
- .split(/\s+/)
50
- .map((part) => part.length === 0
51
- ? part
52
- : part.charAt(0).toUpperCase() + part.slice(1))
54
+ .split(/[\s_]+/)
55
+ .filter((part) => part.length > 0)
56
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
53
57
  .join(" ");
54
58
  }
55
59
  function normalizeApiDisplayName(rawName, properties) {
@@ -2,8 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildScanPersonalDataLayers = buildScanPersonalDataLayers;
4
4
  const identities_1 = require("../../eval-layers/identities");
5
- function lineSnippet(content, startLine, endLine) {
6
- const lines = content.split(/\r?\n/);
5
+ function lineSnippet(lines, startLine, endLine) {
7
6
  const slice = lines.slice(startLine - 1, endLine);
8
7
  if (slice.length === 0) {
9
8
  return undefined;
@@ -13,10 +12,25 @@ function lineSnippet(content, startLine, endLine) {
13
12
  }
14
13
  function buildScanPersonalDataLayers(inventory) {
15
14
  const contentByPath = new Map(inventory.files.map((file) => [file.path, file.content]));
15
+ // Split each file into lines once, not once per occurrence: a file with thousands of
16
+ // occurrences (i18n catalogs, generated clients) otherwise re-splits its whole text for
17
+ // every one of them.
18
+ const linesByPath = new Map();
19
+ const linesOf = (filePath) => {
20
+ let lines = linesByPath.get(filePath);
21
+ if (lines)
22
+ return lines;
23
+ const content = contentByPath.get(filePath);
24
+ if (content === undefined)
25
+ return undefined;
26
+ lines = content.split(/\r?\n/);
27
+ linesByPath.set(filePath, lines);
28
+ return lines;
29
+ };
16
30
  const occurrences = inventory.hits.map((hit) => {
17
- const content = contentByPath.get(hit.evidence.filePath);
18
- const code = content !== undefined
19
- ? lineSnippet(content, hit.evidence.startLine, hit.evidence.endLine)
31
+ const lines = linesOf(hit.evidence.filePath);
32
+ const code = lines !== undefined
33
+ ? lineSnippet(lines, hit.evidence.startLine, hit.evidence.endLine)
20
34
  : undefined;
21
35
  return {
22
36
  id: (0, identities_1.occurrenceIdentity)(hit.id, hit.evidence.filePath, hit.evidence.startLine),
@@ -46,7 +60,7 @@ function buildScanPersonalDataLayers(inventory) {
46
60
  const occurrenceId = (0, identities_1.occurrenceIdentity)(hit.id, hit.evidence.filePath, hit.evidence.startLine);
47
61
  let entry = dataItemsById.get(id);
48
62
  if (!entry) {
49
- entry = { labels: new Set(hit.labels), occurrenceIds: [], groups: new Map() };
63
+ entry = { labels: new Set(hit.labels), occurrenceIds: new Set(), groups: new Map() };
50
64
  dataItemsById.set(id, entry);
51
65
  }
52
66
  else {
@@ -54,16 +68,14 @@ function buildScanPersonalDataLayers(inventory) {
54
68
  entry.labels.add(label);
55
69
  }
56
70
  }
57
- if (!entry.occurrenceIds.includes(occurrenceId)) {
58
- entry.occurrenceIds.push(occurrenceId);
59
- }
71
+ // Sets keep first-seen order, as the arrays with an `includes` check did, without the
72
+ // quadratic scan.
73
+ entry.occurrenceIds.add(occurrenceId);
60
74
  // A location-named singleton (`email~file:line`) is a occurrence no evidence grouped; it
61
75
  // stays on the occurrence for external labels but is not listed as a data item group.
62
76
  if (hit.group && !hit.group.startsWith(`${hit.id}~`)) {
63
- const groupOccurrences = entry.groups.get(hit.group) ?? [];
64
- if (!groupOccurrences.includes(occurrenceId)) {
65
- groupOccurrences.push(occurrenceId);
66
- }
77
+ const groupOccurrences = entry.groups.get(hit.group) ?? new Set();
78
+ groupOccurrences.add(occurrenceId);
67
79
  entry.groups.set(hit.group, groupOccurrences);
68
80
  }
69
81
  }
@@ -75,7 +87,7 @@ function buildScanPersonalDataLayers(inventory) {
75
87
  ...(entry.groups.size > 0
76
88
  ? {
77
89
  groups: [...entry.groups.entries()]
78
- .map(([groupId, occurrenceIds]) => ({ id: groupId, occurrenceIds }))
90
+ .map(([groupId, occurrenceIds]) => ({ id: groupId, occurrenceIds: [...occurrenceIds] }))
79
91
  .sort((left, right) => left.id.localeCompare(right.id)),
80
92
  }
81
93
  : {}),
@@ -7,7 +7,9 @@ const build_scan_personal_data_layers_1 = require("./build-scan-personal-data-la
7
7
  async function enrichOrchestratorResultWithPersonalDataLayers(rootPath, result) {
8
8
  await (0, personal_data_inventory_1.ensureDeclarationEngine)();
9
9
  const inventory = result.ledgerContext
10
- ? (0, personal_data_inventory_1.buildPersonalDataInventoryFromIngest)(result.ledgerContext.allIngestedFiles, result.ledgerContext.ingestOutcomes, await (0, schema_files_1.readSchemaFiles)(rootPath))
10
+ ? (0, personal_data_inventory_1.buildPersonalDataInventoryFromIngest)(result.ledgerContext.allIngestedFiles, result.ledgerContext.ingestOutcomes, await (0, schema_files_1.readSchemaFiles)(rootPath, {
11
+ excludePaths: result.ledgerContext.config.excludePaths,
12
+ }))
11
13
  : await (0, personal_data_inventory_1.buildPersonalDataInventory)(rootPath);
12
14
  const { occurrences, dataItems } = (0, build_scan_personal_data_layers_1.buildScanPersonalDataLayers)(inventory);
13
15
  return { ...result, occurrences, dataItems };
@@ -1,7 +1,25 @@
1
1
  import type { DetectedComponent } from "../core/types/component";
2
2
  import type { DetectedDataFlow } from "../core/types/data-flow";
3
3
  import type { FileInfo } from "../core/types/file";
4
+ type EnclosingScope = {
5
+ startLine: number;
6
+ endLine: number;
7
+ readonly text: string;
8
+ };
9
+ /**
10
+ * The enclosing scope of each line of one file, in O(n log n) per file.
11
+ *
12
+ * A line with no scope header above it is its own scope start, so a file without
13
+ * function or class headers (a generated PHP baseline, a config array) has one scope
14
+ * per line, each running to the end of the file. Caching the joined text of those
15
+ * scopes kept O(lines^2) bytes alive and exhausted the heap on a 1.7 MB file. Only scope
16
+ * end lines are cached; `text` is joined on read and only for lines that need it. Scope
17
+ * ends come from a min segment tree over brace depth and a per-indent index of Ruby
18
+ * `end` lines, so no lookup scans forward through the file.
19
+ */
20
+ export declare function enclosingScopeFinder(lines: string[]): (lineIndex: number) => EnclosingScope;
4
21
  export declare function detectIntraComponentLineage(files: FileInfo[], components: DetectedComponent[], startIndex: number): {
5
22
  flows: DetectedDataFlow[];
6
23
  nextIndex: number;
7
24
  };
25
+ export {};
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.enclosingScopeFinder = enclosingScopeFinder;
3
4
  exports.detectIntraComponentLineage = detectIntraComponentLineage;
4
5
  const pii_signal_rules_1 = require("../pii-signals/pii-signal-rules");
5
6
  const component_evidence_resolution_1 = require("./component-evidence-resolution");
@@ -295,9 +296,15 @@ function countIndent(line) {
295
296
  return match ? match[1].replace(/\t/g, " ").length : 0;
296
297
  }
297
298
  /**
298
- * The enclosing scope of each line of one file. Scope headers are found in one pass and
299
- * scope bodies are cached by header line, so a file costs linear time rather than a
300
- * backward search and a forward brace scan for every line.
299
+ * The enclosing scope of each line of one file, in O(n log n) per file.
300
+ *
301
+ * A line with no scope header above it is its own scope start, so a file without
302
+ * function or class headers (a generated PHP baseline, a config array) has one scope
303
+ * per line, each running to the end of the file. Caching the joined text of those
304
+ * scopes kept O(lines^2) bytes alive and exhausted the heap on a 1.7 MB file. Only scope
305
+ * end lines are cached; `text` is joined on read and only for lines that need it. Scope
306
+ * ends come from a min segment tree over brace depth and a per-indent index of Ruby
307
+ * `end` lines, so no lookup scans forward through the file.
301
308
  */
302
309
  function enclosingScopeFinder(lines) {
303
310
  const nearestHeader = new Array(lines.length);
@@ -310,78 +317,130 @@ function enclosingScopeFinder(lines) {
310
317
  }
311
318
  nearestHeader[index] = last;
312
319
  }
313
- const cache = new Map();
320
+ const findScopeEnd = scopeEndFinder(lines);
321
+ // Scope start -> last line index of the scope; null for a Ruby scope without its `end`.
322
+ const ends = new Map();
314
323
  return (lineIndex) => {
315
324
  const header = nearestHeader[lineIndex] ?? -1;
316
325
  const scopeStart = header >= 0 ? header : lineIndex;
317
- const cached = cache.get(scopeStart);
318
- if (cached)
319
- return cached;
320
- const scope = findEnclosingScope(lines, lineIndex, scopeStart);
321
- // A Ruby scope without its closing `end` ends at the line asked about: not cacheable.
322
- cache.set(scopeStart, scope.unclosed ? null : scope.result);
323
- return scope.result;
326
+ let end = ends.get(scopeStart);
327
+ if (end === undefined) {
328
+ end = findScopeEnd(scopeStart);
329
+ ends.set(scopeStart, end);
330
+ }
331
+ // A Ruby scope without its closing `end` ends at the line asked about.
332
+ const scopeEnd = end ?? lineIndex;
333
+ return {
334
+ startLine: scopeStart + 1,
335
+ endLine: scopeEnd + 1,
336
+ get text() {
337
+ return lines.slice(scopeStart, scopeEnd + 1).join("\n");
338
+ },
339
+ };
324
340
  };
325
341
  }
326
- function findEnclosingScope(lines, lineIndex, scopeStart) {
327
- let scopeEnd = lineIndex;
328
- let unclosed = false;
329
- const scopeLine = lines[scopeStart] ?? "";
330
- const isRubyScope = /^\s*(?:def|class|module)\s+/.test(scopeLine);
331
- let bodyStart = scopeStart;
332
- if (!isRubyScope) {
333
- for (let index = scopeStart; index < lines.length; index += 1) {
334
- if ((lines[index] ?? "").includes("{")) {
335
- bodyStart = index;
336
- break;
337
- }
342
+ /**
343
+ * Last line index of the scope that starts at `scopeStart`, or null for a Ruby scope
344
+ * without a matching `end`.
345
+ *
346
+ * Brace scopes: the body starts at the first line at or after the scope start that holds
347
+ * a `{` and ends at the first later line where the running brace depth, counted from the
348
+ * body start, is back to zero or below. Without such a line (or without any `{`) the
349
+ * scope runs to the end of the file. Ruby scopes (`def`/`class`/`module`) end at the first
350
+ * later `end` line with the same indent.
351
+ */
352
+ function scopeEndFinder(lines) {
353
+ const count = lines.length;
354
+ const lastIndex = count - 1;
355
+ // depthAfter[i]: net `{` minus `}` over lines 0..i.
356
+ const depthAfter = new Int32Array(count);
357
+ // nextOpenLine[i]: first line index >= i that holds a `{`, or -1.
358
+ const nextOpenLine = new Int32Array(count + 1);
359
+ let depth = 0;
360
+ for (let index = 0; index < count; index += 1) {
361
+ const line = lines[index] ?? "";
362
+ for (let offset = 0; offset < line.length; offset += 1) {
363
+ const code = line.charCodeAt(offset);
364
+ if (code === 123)
365
+ depth += 1;
366
+ else if (code === 125)
367
+ depth -= 1;
338
368
  }
339
- }
340
- let braceDepth = 0;
341
- let foundOpenBrace = false;
342
- if (!isRubyScope) {
343
- for (let index = bodyStart; index < lines.length; index += 1) {
344
- const line = lines[index] ?? "";
345
- for (const char of line) {
346
- if (char === "{") {
347
- braceDepth += 1;
348
- foundOpenBrace = true;
349
- }
350
- else if (char === "}") {
351
- braceDepth -= 1;
352
- }
353
- }
354
- scopeEnd = index;
355
- if (foundOpenBrace && braceDepth <= 0 && index > bodyStart) {
356
- break;
357
- }
369
+ depthAfter[index] = depth;
370
+ }
371
+ nextOpenLine[count] = -1;
372
+ for (let index = count - 1; index >= 0; index -= 1) {
373
+ nextOpenLine[index] = (lines[index] ?? "").includes("{") ? index : nextOpenLine[index + 1];
374
+ }
375
+ const firstDepthAtMost = firstAtMostFinder(depthAfter);
376
+ let rubyEndsByIndent;
377
+ return (scopeStart) => {
378
+ const scopeLine = lines[scopeStart] ?? "";
379
+ if (/^\s*(?:def|class|module)\s+/.test(scopeLine)) {
380
+ rubyEndsByIndent ??= rubyEndLinesByIndent(lines);
381
+ const candidates = rubyEndsByIndent.get(countIndent(scopeLine)) ?? [];
382
+ const position = firstGreaterThan(candidates, scopeStart);
383
+ return position < candidates.length ? candidates[position] : null;
358
384
  }
359
- }
360
- if (!foundOpenBrace) {
361
- if (isRubyScope) {
362
- unclosed = true;
363
- const scopeIndent = countIndent(scopeLine);
364
- for (let index = scopeStart + 1; index < lines.length; index += 1) {
365
- const line = lines[index] ?? "";
366
- if (!/^\s*end\b/.test(line)) {
367
- continue;
368
- }
369
- if (countIndent(line) === scopeIndent) {
370
- scopeEnd = index;
371
- unclosed = false;
372
- break;
373
- }
374
- }
385
+ const bodyStart = nextOpenLine[scopeStart];
386
+ if (bodyStart < 0 || bodyStart >= lastIndex) {
387
+ return lastIndex;
375
388
  }
376
- }
377
- return {
378
- result: {
379
- startLine: scopeStart + 1,
380
- endLine: scopeEnd + 1,
381
- text: lines.slice(scopeStart, scopeEnd + 1).join("\n"),
382
- },
383
- unclosed,
389
+ const depthBeforeBody = bodyStart > 0 ? depthAfter[bodyStart - 1] : 0;
390
+ const closing = firstDepthAtMost(bodyStart + 1, depthBeforeBody);
391
+ return closing >= 0 ? closing : lastIndex;
392
+ };
393
+ }
394
+ function rubyEndLinesByIndent(lines) {
395
+ const byIndent = new Map();
396
+ lines.forEach((line, index) => {
397
+ if (!/^\s*end\b/.test(line))
398
+ return;
399
+ const indent = countIndent(line);
400
+ const list = byIndent.get(indent);
401
+ if (list)
402
+ list.push(index);
403
+ else
404
+ byIndent.set(indent, [index]);
405
+ });
406
+ return byIndent;
407
+ }
408
+ /** Position of the first value in ascending `values` that is greater than `target`. */
409
+ function firstGreaterThan(values, target) {
410
+ let low = 0;
411
+ let high = values.length;
412
+ while (low < high) {
413
+ const middle = (low + high) >> 1;
414
+ if (values[middle] > target)
415
+ high = middle;
416
+ else
417
+ low = middle + 1;
418
+ }
419
+ return low;
420
+ }
421
+ /**
422
+ * Returns a lookup for the first index >= `from` whose value is <= `limit` (or -1), in
423
+ * O(log n) per lookup over a min segment tree.
424
+ */
425
+ function firstAtMostFinder(values) {
426
+ let size = 1;
427
+ while (size < values.length)
428
+ size *= 2;
429
+ const tree = new Int32Array(size * 2).fill(0x7fffffff);
430
+ tree.set(values, size);
431
+ for (let node = size - 1; node >= 1; node -= 1) {
432
+ tree[node] = Math.min(tree[node * 2], tree[node * 2 + 1]);
433
+ }
434
+ const search = (node, low, high, from, limit) => {
435
+ if (high < from || tree[node] > limit)
436
+ return -1;
437
+ if (low === high)
438
+ return low;
439
+ const middle = (low + high) >> 1;
440
+ const left = search(node * 2, low, middle, from, limit);
441
+ return left >= 0 ? left : search(node * 2 + 1, middle + 1, high, from, limit);
384
442
  };
443
+ return (from, limit) => (from >= values.length ? -1 : search(1, 0, size - 1, from, limit));
385
444
  }
386
445
  function isClassScopeLine(line) {
387
446
  return CLASS_DEF_PATTERNS.some((pattern) => pattern.test(line));
@@ -24,6 +24,8 @@ export { dedupeDataFlows } from "./data-flow/dedupe";
24
24
  export { loadClassifierConfig } from "./classifier/config";
25
25
  export { hostMatchesOrganizationDomains, normalizeOrganizationDomains, } from "./classifier/external-url-third-party";
26
26
  export { DETECTABLE_PROPERTY_KEYS } from "./classifier/enhance-defaults";
27
+ export { canonicalFrameworkId, frameworkDisplayName, } from "./patterns/frontend-frameworks";
28
+ export { toDisplayName } from "./classifier/naming";
27
29
  export { runAnalyzers } from "./analyzers/registry";
28
30
  export * from "./core/schema";
29
31
  export * from "./core/types";
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.DATA_ACTIONS = exports.tagFindingsWithServiceSections = exports.discoverServiceSections = exports.runAnalyzers = exports.DETECTABLE_PROPERTY_KEYS = exports.normalizeOrganizationDomains = exports.hostMatchesOrganizationDomains = exports.loadClassifierConfig = exports.dedupeDataFlows = exports.appendTerraformBareProviderAttachmentFlows = exports.shouldSkipDirectoryName = exports.DEFAULT_EXCLUDED_FILE_GLOBS = exports.toPosixPath = exports.isPathIgnored = exports.gitignoreRulesForDir = exports.gitignorePatternToRegex = exports.isSensitiveEnvPath = exports.resolveScanFilesystemEntry = exports.ingestFileSystem = exports.sortDataFlowsDeterministically = exports.STABLE_FLOW_ID_PREFIX = exports.STABLE_FLOW_ID_PATTERN = exports.STABLE_COMPONENT_ID_PREFIX = exports.STABLE_COMPONENT_ID_PATTERN = exports.stableFlowKey = exports.stableFlowId = exports.stableComponentId = exports.resolvedStableComponentKey = exports.normalizeFlowEndpoint = exports.buildComponentKeyById = exports.assignStableEntityIdsWithMaps = exports.assignStableEntityIds = exports.assignStableComponentIds = exports.stableComponentKey = exports.collectEvalFindings = exports.DATAPARADE_GRAPH_SCHEMA = exports.DATAPARADE_GRAPH_FILE = exports.writeKnowledgeGraph = exports.buildDataParadeGraph = exports.loadGraphifyGraph = exports.runGraphify = exports.selectPrimaryDataAction = exports.buildDiagramGraphFromScanResult = exports.buildScanPersonalDataLayers = exports.enrichOrchestratorResultWithPersonalDataLayers = exports.runDeterministicScanPhases = exports.finalizeDeterministicScanResult = exports.emitScanProgress = exports.scan = exports.createDefaultScanConfiguration = void 0;
18
- exports.runDataActionPhase = exports.hasVerb = exports.readDataActions = exports.mergeOneAssignment = exports.mergeAssignmentsOntoComponents = exports.DATA_ACTION_RULE_LANGUAGES = exports.ruleAppliesToLanguage = exports.clearDataActionRulesCacheForTest = exports.loadDataActionRules = exports.loadDataActionRuleCatalog = exports.TERRAFORM_GATEWAY_SUBTYPES = exports.SUBTYPE_STORE_SUBTYPES = exports.deriveFromSubtypes = exports.pathsReferToSameFile = exports.deriveFromPatterns = exports.STORAGE_SUBTYPES = exports.deriveFromTopology = exports.normalizeDataActionToken = exports.normalizeDataAction = exports.isDataAction = exports.DATA_ACTION_SET = exports.DATA_ACTION_FRAMEWORK_ANCHORS = exports.DATA_ACTION_ALIASES = void 0;
17
+ exports.runAnalyzers = exports.toDisplayName = exports.frameworkDisplayName = exports.canonicalFrameworkId = exports.DETECTABLE_PROPERTY_KEYS = exports.normalizeOrganizationDomains = exports.hostMatchesOrganizationDomains = exports.loadClassifierConfig = exports.dedupeDataFlows = exports.appendTerraformBareProviderAttachmentFlows = exports.shouldSkipDirectoryName = exports.DEFAULT_EXCLUDED_FILE_GLOBS = exports.toPosixPath = exports.isPathIgnored = exports.gitignoreRulesForDir = exports.gitignorePatternToRegex = exports.isSensitiveEnvPath = exports.resolveScanFilesystemEntry = exports.ingestFileSystem = exports.sortDataFlowsDeterministically = exports.STABLE_FLOW_ID_PREFIX = exports.STABLE_FLOW_ID_PATTERN = exports.STABLE_COMPONENT_ID_PREFIX = exports.STABLE_COMPONENT_ID_PATTERN = exports.stableFlowKey = exports.stableFlowId = exports.stableComponentId = exports.resolvedStableComponentKey = exports.normalizeFlowEndpoint = exports.buildComponentKeyById = exports.assignStableEntityIdsWithMaps = exports.assignStableEntityIds = exports.assignStableComponentIds = exports.stableComponentKey = exports.collectEvalFindings = exports.DATAPARADE_GRAPH_SCHEMA = exports.DATAPARADE_GRAPH_FILE = exports.writeKnowledgeGraph = exports.buildDataParadeGraph = exports.loadGraphifyGraph = exports.runGraphify = exports.selectPrimaryDataAction = exports.buildDiagramGraphFromScanResult = exports.buildScanPersonalDataLayers = exports.enrichOrchestratorResultWithPersonalDataLayers = exports.runDeterministicScanPhases = exports.finalizeDeterministicScanResult = exports.emitScanProgress = exports.scan = exports.createDefaultScanConfiguration = void 0;
18
+ exports.runDataActionPhase = exports.hasVerb = exports.readDataActions = exports.mergeOneAssignment = exports.mergeAssignmentsOntoComponents = exports.DATA_ACTION_RULE_LANGUAGES = exports.ruleAppliesToLanguage = exports.clearDataActionRulesCacheForTest = exports.loadDataActionRules = exports.loadDataActionRuleCatalog = exports.TERRAFORM_GATEWAY_SUBTYPES = exports.SUBTYPE_STORE_SUBTYPES = exports.deriveFromSubtypes = exports.pathsReferToSameFile = exports.deriveFromPatterns = exports.STORAGE_SUBTYPES = exports.deriveFromTopology = exports.normalizeDataActionToken = exports.normalizeDataAction = exports.isDataAction = exports.DATA_ACTION_SET = exports.DATA_ACTION_FRAMEWORK_ANCHORS = exports.DATA_ACTION_ALIASES = exports.DATA_ACTIONS = exports.tagFindingsWithServiceSections = exports.discoverServiceSections = void 0;
19
19
  var orchestrator_1 = require("./core/pipeline/orchestrator");
20
20
  Object.defineProperty(exports, "createDefaultScanConfiguration", { enumerable: true, get: function () { return orchestrator_1.createDefaultScanConfiguration; } });
21
21
  Object.defineProperty(exports, "scan", { enumerable: true, get: function () { return orchestrator_1.scan; } });
@@ -82,6 +82,11 @@ Object.defineProperty(exports, "hostMatchesOrganizationDomains", { enumerable: t
82
82
  Object.defineProperty(exports, "normalizeOrganizationDomains", { enumerable: true, get: function () { return external_url_third_party_1.normalizeOrganizationDomains; } });
83
83
  var enhance_defaults_1 = require("./classifier/enhance-defaults");
84
84
  Object.defineProperty(exports, "DETECTABLE_PROPERTY_KEYS", { enumerable: true, get: function () { return enhance_defaults_1.DETECTABLE_PROPERTY_KEYS; } });
85
+ var frontend_frameworks_1 = require("./patterns/frontend-frameworks");
86
+ Object.defineProperty(exports, "canonicalFrameworkId", { enumerable: true, get: function () { return frontend_frameworks_1.canonicalFrameworkId; } });
87
+ Object.defineProperty(exports, "frameworkDisplayName", { enumerable: true, get: function () { return frontend_frameworks_1.frameworkDisplayName; } });
88
+ var naming_1 = require("./classifier/naming");
89
+ Object.defineProperty(exports, "toDisplayName", { enumerable: true, get: function () { return naming_1.toDisplayName; } });
85
90
  var registry_1 = require("./analyzers/registry");
86
91
  Object.defineProperty(exports, "runAnalyzers", { enumerable: true, get: function () { return registry_1.runAnalyzers; } });
87
92
  __exportStar(require("./core/schema"), exports);
@@ -10,6 +10,11 @@ export interface IngestOptions {
10
10
  excludePaths?: string[];
11
11
  onWarning?: (warning: string) => void;
12
12
  }
13
+ /**
14
+ * True when a path relative to the scan root matches one of the exclude patterns
15
+ * (defaults plus `--exclude`). Walks call it on directories to prune them.
16
+ */
17
+ export declare function isExcludedByUserPatterns(relativePath: string, isDirectory: boolean, excludePaths: readonly string[]): boolean;
13
18
  /**
14
19
  * Resolve a user-supplied scan path to a directory (for config, Terraform cwd,
15
20
  * section discovery) and an ingest target (directory walk or a single file).
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.DEFAULT_MAX_TOTAL_BYTES = exports.DEFAULT_MAX_FILE_COUNT = exports.DEFAULT_MAX_FILE_SIZE_BYTES = void 0;
37
+ exports.isExcludedByUserPatterns = isExcludedByUserPatterns;
37
38
  exports.resolveScanFilesystemEntry = resolveScanFilesystemEntry;
38
39
  exports.ingestFileSystemWithOutcomes = ingestFileSystemWithOutcomes;
39
40
  exports.ingestFileSystem = ingestFileSystem;
@@ -49,6 +50,10 @@ exports.DEFAULT_MAX_TOTAL_BYTES = 200 * 1024 * 1024; // 200MB
49
50
  function normalizeUserPattern(pattern) {
50
51
  return (0, gitignore_1.toPosixPath)(pattern.replace(/^\.\/+/, "").trim());
51
52
  }
53
+ /**
54
+ * True when a path relative to the scan root matches one of the exclude patterns
55
+ * (defaults plus `--exclude`). Walks call it on directories to prune them.
56
+ */
52
57
  function isExcludedByUserPatterns(relativePath, isDirectory, excludePaths) {
53
58
  const rel = (0, gitignore_1.toPosixPath)(relativePath);
54
59
  for (const rawPattern of excludePaths) {
@@ -6,7 +6,24 @@ export type IgnoreRule = {
6
6
  regex: RegExp;
7
7
  };
8
8
  export declare function toPosixPath(p: string): string;
9
+ /**
10
+ * Glob to regex for user exclude patterns, matched against the path relative to the
11
+ * scan root:
12
+ * - * matches any chars except path separator
13
+ * - ** matches across directories
14
+ * - ? matches a single non-separator
15
+ */
9
16
  export declare function gitignorePatternToRegex(pattern: string, dirOnly: boolean): RegExp;
17
+ /**
18
+ * Regex for one `.gitignore` line, matched against the path relative to the
19
+ * `.gitignore`'s directory, following git's rules:
20
+ * - a leading `/` anchors the pattern to that directory;
21
+ * - a pattern with no other `/` matches a name at any depth (`build`, `*.log`);
22
+ * - a pattern with a `/` in the middle is anchored (`src/gen`);
23
+ * - a leading or inner `**` segment matches zero or more directories.
24
+ * A match on a directory also ignores everything under it.
25
+ */
26
+ export declare function gitignoreLineToRegex(line: string): RegExp;
10
27
  export declare function readGitignore(dir: string): Promise<IgnoreRule[]>;
11
28
  export declare function gitignoreRulesForDir(currentDir: string, accumulatedRules: IgnoreRule[]): Promise<IgnoreRule[]>;
12
29
  export declare function isPathIgnored(absolutePath: string, isDirectory: boolean, rules: IgnoreRule[]): boolean;