fallow_types/extract.rs
1//! Module extraction types.
2
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use oxc_span::Span;
7
8use crate::discover::FileId;
9use crate::suppress::{Suppression, UnknownSuppressionKind};
10
11/// Extracted module information from a single file.
12///
13/// The `Arc<[T]>` fields are immutable after extraction and are shared by
14/// refcount with the resolver's per-file output, so the resolve/graph path
15/// does not deep-copy per-file extraction payloads.
16#[derive(Debug, Clone)]
17pub struct ModuleInfo {
18 /// Unique identifier for this file.
19 pub file_id: FileId,
20 /// All export declarations in this module.
21 pub exports: Arc<[ExportInfo]>,
22 /// All import declarations in this module.
23 pub imports: Vec<ImportInfo>,
24 /// All re-export declarations (e.g., `export { foo } from './bar'`).
25 pub re_exports: Vec<ReExportInfo>,
26 /// All dynamic `import()` calls with string literal sources.
27 pub dynamic_imports: Vec<DynamicImportInfo>,
28 /// Dynamic import patterns.
29 pub dynamic_import_patterns: Vec<DynamicImportPattern>,
30 /// All `require()` calls.
31 pub require_calls: Vec<RequireCallInfo>,
32 /// Package names statically referenced through package path resolution.
33 pub package_path_references: Box<[String]>,
34 /// Static member access expressions (e.g., `Status.Active`).
35 pub member_accesses: Arc<[MemberAccess]>,
36 /// Typed semantic facts produced by extraction for cross-layer analysis.
37 ///
38 /// This carries facts that were previously encoded as synthetic
39 /// `member_accesses` strings. Extraction and analysis now use typed facts.
40 pub semantic_facts: Arc<[SemanticFact]>,
41 /// Identifiers used in whole-object access patterns.
42 pub whole_object_uses: Arc<[String]>,
43 /// Whether this module uses CommonJS exports.
44 pub has_cjs_exports: bool,
45 /// Whether this module declares an Angular component `templateUrl`.
46 pub has_angular_component_template_url: bool,
47 /// xxh3 hash of the file content for incremental caching.
48 pub content_hash: u64,
49 /// Inline suppression directives parsed from comments.
50 pub suppressions: Vec<Suppression>,
51 /// Suppression tokens that did not parse to any known `IssueKind`.
52 /// Surfaced as `StaleSuppression` findings via `find_stale` so users see
53 /// typos or obsolete kind names instead of having the entire marker
54 /// silently discarded. See issue #449.
55 pub unknown_suppression_kinds: Vec<UnknownSuppressionKind>,
56 /// Local names of import bindings that are never referenced in this file.
57 /// Populated via `oxc_semantic` scope analysis. Used at graph-build time
58 /// to skip adding references for imports whose binding is never read,
59 /// improving unused-export detection precision.
60 pub unused_import_bindings: Vec<String>,
61 /// Local import bindings that are referenced from TypeScript type positions.
62 /// Used to distinguish value-namespace and type-namespace references when a
63 /// module exports both `const X` and `type X`.
64 pub type_referenced_import_bindings: Vec<String>,
65 /// Local import bindings referenced from runtime/value positions.
66 pub value_referenced_import_bindings: Vec<String>,
67 /// Pre-computed byte offsets where each line starts.
68 pub line_offsets: Vec<u32>,
69 /// Per-function complexity metrics.
70 pub complexity: Vec<FunctionComplexity>,
71 /// Feature flag use sites.
72 pub flag_uses: Vec<FlagUse>,
73 /// Heritage metadata for exported classes that declare `implements`.
74 pub class_heritage: Vec<ClassHeritageInfo>,
75 /// Exported free-function factories that provably return one class instance
76 /// (`export function useApi() { return new RESTApi() }`). Origin-module proof
77 /// that an exported function returns a class instance, so a cross-module
78 /// `const x = useApi(); x.member` consumer can credit the returned class.
79 /// See issue #1441 (Part A).
80 pub exported_factory_returns: Arc<[FactoryReturnExport]>,
81 /// Exported factories that return an OBJECT LITERAL whose property values are
82 /// class instances (`export function createUi() { return { orders: factory.ordersPage } }`).
83 /// Each entry maps a dotted property path (`orders`, `invoke.dashboard`) to the
84 /// returned class's local name within the factory module, so a cross-module
85 /// `const ui = createUi(); ui.orders.member` consumer can credit the class. Names
86 /// are local to this module; resolution is deferred to analyze time. See issue #1858.
87 pub exported_factory_return_object_shapes: Arc<[FactoryReturnObjectShapeExport]>,
88 /// Named-type property types declared by this module's top-level interfaces
89 /// and type-literal aliases (`interface Opts { c: OptDep }`). Names are
90 /// local to this module; resolution is deferred to analyze time. Consumed
91 /// by the `unused-class-member` typed-property-hop join and the Playwright
92 /// fixture-type resolution. See issue #1785.
93 pub type_member_types: Arc<[TypeMemberTypeEntry]>,
94 /// Angular `InjectionToken<Interface>` declarations, as
95 /// `(token_export_name, interface_name)` pairs. Recorded only for
96 /// `new InjectionToken<I>(...)` initializers whose `InjectionToken` is
97 /// imported from `@angular/core`. The analyze layer follows the token's
98 /// interface type argument to the classes that `implement` it so a template
99 /// member call through `inject(TOKEN)` credits the concrete implementation.
100 /// See issue #920 (follow-up to #911 / #913).
101 pub injection_tokens: Vec<(String, String)>,
102 /// Local type-capable declarations.
103 pub local_type_declarations: Vec<LocalTypeDeclaration>,
104 /// Type references in exported public signatures.
105 pub public_signature_type_references: Vec<PublicSignatureTypeReference>,
106 /// Aliases of namespace imports re-exported through an object literal.
107 pub namespace_object_aliases: Vec<NamespaceObjectAlias>,
108 /// Deduped Iconify collection prefixes found in static icon props.
109 pub iconify_prefixes: Vec<String>,
110 /// Deduped Nuxt UI `i-<collection>-<icon>` icon class suffixes found in
111 /// static script-side icon properties.
112 pub iconify_icon_names: Vec<String>,
113 /// Bare identifiers that may be resolved by framework auto-imports.
114 pub auto_import_candidates: Vec<String>,
115 /// File-level string directives in source order (e.g. `"use client"`,
116 /// `"use server"`, `"use strict"`). Captured from `Program::directives`.
117 /// Consumed by the security `client-server-leak` detector to identify
118 /// React Server Component client boundaries.
119 pub directives: Vec<String>,
120 /// Byte-offset starts of dynamic `import()` expressions wrapped in
121 /// `next/dynamic(() => import('./X'), { ssr: false })`. The ssr:false option
122 /// is Next.js's sanctioned way to pull a client-only module, so a server-only
123 /// module reached ONLY through such an import is NOT a client-server leak. The
124 /// security `client-server-leak` BFS resolves each dynamic import to a graph
125 /// edge; these span starts let the BFS exclude exactly those edges (matched
126 /// against the edge's `import_span`). Empty for files with no ssr:false
127 /// dynamic import. Captured only by JS/TS extraction.
128 pub client_only_dynamic_import_spans: Vec<u32>,
129 /// Captured security sink sites (category-blind). Consumed by the
130 /// catalogue-driven `tainted_sink` detector. Captured only by JS/TS
131 /// extraction; empty for CSS/MDX/etc. See `security_matchers.toml`.
132 pub security_sinks: Vec<SinkSite>,
133 /// Count of sink-shaped nodes whose callee could not be flattened to a
134 /// static path (dynamic dispatch, computed members, aliased bindings).
135 /// Surfaced in-band so an empty catalogue result with a non-zero count is
136 /// not a clean bill.
137 pub security_sinks_skipped: u32,
138 /// Compact span-level diagnostics for skipped security sink callees. Kept
139 /// next to `security_sinks_skipped` so warm-cache and cold-cache security
140 /// output can explain where the blind spots are concentrated without source
141 /// snippets.
142 pub security_unresolved_callee_sites: Vec<SkippedSecurityCalleeSite>,
143 /// Local bindings whose initializer (or destructured object) is a flattened
144 /// member-access path. Used by the security `tainted_sink` detector to
145 /// back-trace a sink argument to a known untrusted source: the analyze layer
146 /// matches each binding's `source_path` against the data-driven source
147 /// catalogue (`security_matchers.toml` `[[source]]` rows) and treats the
148 /// matching `local` names as source-tainted. Intra-module and name-based
149 /// (no scope analysis); a conservative association, never a taint proof.
150 pub tainted_bindings: Vec<TaintedBinding>,
151 /// Sink arguments that were recognized as sanitizer calls at extraction
152 /// time. Used for direct sink calls such as
153 /// `el.innerHTML = DOMPurify.sanitize(input)`.
154 pub sanitized_sink_args: Vec<SanitizedSinkArg>,
155 /// Known defensive control call sites found in this module. Consumed only by
156 /// the `fallow security --surface` agent JSON path.
157 pub security_control_sites: Vec<SecurityControlSite>,
158 /// Statically flattenable callee paths invoked in this module, deduped per
159 /// unique path (first occurrence wins). Consumed by the
160 /// `boundaries.calls.forbidden` detector. Captured unconditionally because
161 /// extraction is config-blind; the per-module cost is bounded by the
162 /// unique-callee count.
163 pub callee_uses: Vec<CalleeUse>,
164 /// `"use client"` / `"use server"` directive strings written as expression
165 /// statements in `program.body` (misplaced, NOT in the leading
166 /// prologue), so the RSC bundler silently ignores them. One entry per
167 /// occurrence. Consumed by the `misplaced-directive` detector. Captured
168 /// only by JS/TS extraction.
169 pub misplaced_directives: Vec<MisplacedDirectiveSite>,
170 /// Export LOCAL NAMES of exported functions / const-arrows whose body has an
171 /// inline `"use server"` directive (`export async function f() { "use server"
172 /// }`), captured in a NON-`"use server"` file. Consumed by the
173 /// `unused-server-action` detector to reclassify an unused inline Server
174 /// Action export out of `unused-export`. Captured only by JS/TS extraction.
175 pub inline_server_action_exports: Vec<String>,
176 /// Vue `provide`/`inject` and Svelte `setContext`/`getContext` call sites
177 /// keyed by an identifier symbol. Consumed by the `unprovided-inject`
178 /// detector to find an inject/getContext whose key is provided nowhere
179 /// project-wide. Only identifier-keyed sites are recorded (string-literal
180 /// and computed keys abstain). Captured by JS/TS and SFC extraction.
181 pub di_key_sites: Vec<DiKeySite>,
182 /// `true` when this module contains a `provide(...)` / `*.provide(...)` /
183 /// `setContext(...)` call whose key argument is NOT a plain identifier
184 /// (spread, computed, member, loop variable). Such a call can provide an
185 /// unknowable key, so the `unprovided-inject` detector abstains on ALL
186 /// inject findings project-wide when any reachable module sets this flag.
187 /// Mirrors the spread-return whole-object abstain used for Pinia stores.
188 pub has_dynamic_provide: bool,
189 /// Local names of import bindings that ARE referenced somewhere in this file
190 /// (script value/type position OR template/markup). The complement of
191 /// `unused_import_bindings` among `imports`. Derived by
192 /// `prepare_analysis_facts` while both source vectors are still present, so
193 /// it remains readable after the owned release path clears them. It is never
194 /// cached and is recomputed on every cache load. Consumed by the
195 /// `unrendered-component` detector to credit a
196 /// Vue/Svelte SFC that some file actually imports-and-uses, distinguishing it
197 /// from a component reachable only through a barrel re-export.
198 pub referenced_import_bindings: Vec<String>,
199 /// Vue `<script setup>` `defineProps` and Svelte 5 `$props()` declared
200 /// props. Consumed by the `unused-component-prop` detector to flag a prop
201 /// referenced nowhere in its own SFC. Each entry carries `used_in_script` /
202 /// `used_in_template`.
203 pub component_props: Vec<ComponentProp>,
204 /// `true` when the template spreads the whole props/attrs object
205 /// (`v-bind="$attrs"` / `v-bind="$props"` / `v-bind="props"`) or the props
206 /// return is destructured with a rest element. Either form can consume a prop
207 /// indirectly, so the detector abstains on the whole file.
208 pub has_props_attrs_fallthrough: bool,
209 /// `true` when the SFC calls `defineExpose(...)`. A prop may be re-exposed,
210 /// so the detector conservatively abstains on the whole file.
211 pub has_define_expose: bool,
212 /// `true` when the SFC calls `defineModel(...)`. Two-way model props are out
213 /// of scope for v1, so the detector abstains on the whole file.
214 pub has_define_model: bool,
215 /// `true` when props were declared through an unharvestable shape, such as a
216 /// Vue type-reference argument or an opaque Svelte `$props()` destructure.
217 /// The detector abstains on the whole file so a prop is never falsely
218 /// flagged.
219 pub has_unharvestable_props: bool,
220 /// Vue `<script setup>` `defineEmits` declared events. Consumed by the
221 /// `unused-component-emit` detector to flag an event emitted nowhere in its
222 /// own SFC. Each entry carries `used`.
223 pub component_emits: Vec<ComponentEmit>,
224 /// Angular component/directive inputs declared via `@Input()` decorators or
225 /// signal `input()` / `input.required()` / `model()` initializers. Consumed
226 /// by the `unused-component-input` detector to flag an input read nowhere in
227 /// its own component. Empty for every non-Angular class.
228 pub angular_inputs: Vec<AngularInputMember>,
229 /// Angular component/directive outputs declared via `@Output()` decorators or
230 /// signal `output()` / `outputFromObservable()` initializers. Consumed by the
231 /// `unused-component-output` detector to flag an output emitted nowhere in its
232 /// own component. A `model()` is recorded as an input only (see
233 /// `AngularOutputMember`). Empty for every non-Angular class.
234 pub angular_outputs: Vec<AngularOutputMember>,
235 /// Angular `@Component` declarations with their `selector` value(s), harvested
236 /// from `@Component({ selector: '...' })` decorators. Consumed by the Angular
237 /// arm of the `unrendered-component` detector. Empty for every non-Angular
238 /// class and for `@Directive`. See `AngularComponentSelector`.
239 pub angular_component_selectors: Vec<AngularComponentSelector>,
240 /// Lit / web-component custom elements REGISTERED in this file via
241 /// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed
242 /// by the Lit arm of the `unrendered-component` detector, which flags a
243 /// registered element whose tag is rendered in NO `html` template
244 /// project-wide. Empty for non-Lit / non-web-component files. See
245 /// `RegisteredCustomElement`.
246 pub registered_custom_elements: Vec<RegisteredCustomElement>,
247 /// Custom-element tag names USED (rendered) in this file's `html` tagged
248 /// templates, e.g. `` html`<x-foo></x-foo>` `` -> `x-foo`. Only hyphenated
249 /// (custom-element) tags are recorded; native HTML tags are excluded by the
250 /// hyphen requirement. The detector unions these project-wide into the
251 /// rendered-tag set. Empty for files with no `html` templates.
252 pub used_custom_element_tags: Vec<String>,
253 /// Custom element selector tag names referenced in this file's Angular
254 /// templates (inline `@Component({ template })` and the linked external
255 /// `templateUrl` `.html` module), e.g. `<app-foo>` -> `app-foo`. Native HTML
256 /// tag names are excluded at harvest. The detector unions these project-wide
257 /// into the used-selector set. Empty for non-Angular files.
258 pub angular_used_selectors: Vec<String>,
259 /// Angular component class names referenced as a route entry or bootstrap
260 /// target: a route `component: Foo` / `loadComponent: () => import().then(m =>
261 /// m.Foo)` value, a `bootstrapApplication(Foo)` argument, or a
262 /// `bootstrap: [Foo]` NgModule entry. These are render-equivalent entry points
263 /// (Angular instantiates them without a template `<tag>`), so the Angular
264 /// `unrendered-component` detector abstains on a component whose class name is
265 /// in the project-wide union. A plain `declarations: [...]` / `imports: [...]`
266 /// registration is intentionally NOT harvested here (that is the dead case the
267 /// rule catches). Empty for non-Angular files.
268 pub angular_entry_component_refs: Vec<String>,
269 /// `true` when this file dynamically renders an Angular component fallow
270 /// cannot attribute to a literal class reference: a
271 /// `ViewContainerRef.createComponent(...)` / `*.createComponent(<ident>)`
272 /// call, or an `*ngComponentOutlet` template binding. The Angular
273 /// `unrendered-component` detector abstains project-wide when ANY reachable
274 /// module sets this (mirroring `unprovided-inject`'s `has_dynamic_provide`),
275 /// since a component could be rendered by a non-literal class reference.
276 pub has_dynamic_component_render: bool,
277 /// `true` when `defineEmits` was called with an unharvestable argument (a
278 /// type-reference type argument such as `defineEmits<MyEmits>()`, a
279 /// non-literal runtime form, or an unbound `defineEmits([...])`). The
280 /// detector abstains on the whole file so an emit is never falsely flagged.
281 pub has_unharvestable_emits: bool,
282 /// `true` when an `emit(<nonLiteral>)` call was seen (the emitted event name
283 /// cannot be known statically). The detector abstains on the whole file.
284 pub has_dynamic_emit: bool,
285 /// `true` when the `defineEmits` return binding was used as a WHOLE value
286 /// (passed to a function, returned, or spread), which can emit any event
287 /// opaquely. The detector abstains on the whole file.
288 pub has_emit_whole_object_use: bool,
289 /// SvelteKit `load()` return-object keys harvested from a
290 /// `+page.{ts,server.ts,js,server.js}` file's terminal return literal.
291 /// Consumed by the `unused-load-data-key` detector. Empty for every file
292 /// that is not a page-load producer (gated by basename at harvest time).
293 pub load_return_keys: Vec<LoadReturnKey>,
294 /// `true` when this file's `load()` body could not be harvested safely (a
295 /// spread return, a non-object/non-literal return, more than one top-level
296 /// `return`, a computed key, or a wrapped/re-exported `load`). The detector
297 /// abstains on the whole file so a key is never falsely flagged.
298 pub has_unharvestable_load: bool,
299 /// `true` when this file passes the whole `data` object opaquely (script
300 /// `const X = data`, `fn(data)` / `fn(...data)`, or template `data={data}` /
301 /// `{...data}` in a route component), so a child can read arbitrary keys the
302 /// detector cannot see. Name-gated on the `data` binding. Read ONLY by the
303 /// `unused-load-data-key` detector, so capturing it for all files is
304 /// byte-identity-safe. See FP-1 in the plan.
305 pub has_load_data_whole_use: bool,
306 /// `true` when this file uses the whole `page.data` / `$page.data` store
307 /// object opaquely (e.g. `Object.values(page.data)`, `{...$page.data}`), so a
308 /// reflective read could consume any route's key. Drives the
309 /// `unused-load-data-key` detector's project-wide abstain. Derived by
310 /// `prepare_analysis_facts` from `whole_object_uses` before the owned release
311 /// path clears that vector. It is never cached and is recomputed each run from
312 /// the cached `whole_object_uses`. Reassignment forms
313 /// (`const all = $page.data`) are not whole-object-tracked and stay out of
314 /// scope, matching the syntactic analyzer's conservative posture.
315 pub has_page_data_store_whole_use: bool,
316 /// `true` when a React Router or Remix route consumes the whole
317 /// `useLoaderData()` result opaquely. Derived by `prepare_analysis_facts`
318 /// from the synthetic route-loader marker before the owned release path
319 /// clears `whole_object_uses`. It is recomputed from cached extraction data.
320 pub has_route_loader_data_whole_use: bool,
321 /// React/JSX component definitions: functions/arrows whose body returns JSX.
322 /// Captured only for `.jsx`/`.tsx` files when a React/Preact dependency is
323 /// plausible. Consumed by the React `unused-component-prop` arm and the
324 /// complexity-fold phase. Empty for non-React files.
325 pub component_functions: Vec<ComponentFunction>,
326 /// React component props (reuses the shared `ComponentProp` struct). For
327 /// React, `used_in_template` is always false and `used_in_script` means
328 /// used-in-body. Empty for non-React files.
329 pub react_props: Vec<ComponentProp>,
330 /// React hook call sites (`useState` / `useEffect` / `useMemo` /
331 /// `useCallback` / custom `use*`). Drives hook-density complexity context.
332 /// Empty for non-React files.
333 pub hook_uses: Vec<HookUse>,
334 /// React render edges: one component rendering another. Captured with the
335 /// child's written name; child-to-`FileId` resolution is deferred to graph
336 /// build. Empty for non-React files.
337 pub render_edges: Vec<RenderEdge>,
338 /// Svelte custom events dispatched via `dispatch('<name>')` where `dispatch`
339 /// is the binding from `const dispatch = createEventDispatcher()`. Consumed
340 /// by the `unused-svelte-event` detector to flag an event dispatched here but
341 /// listened to nowhere project-wide. Each entry carries the literal event
342 /// name and its span. Empty for every non-Svelte file.
343 pub svelte_dispatched_events: Vec<DispatchedEvent>,
344 /// Svelte custom-event listener names harvested from template `on:<name>`
345 /// bindings on COMPONENT tags (PascalCase tag names). Lowercase DOM-element
346 /// `on:click` is a DOM event, not a custom event, and is excluded. Unioned
347 /// project-wide by the `unused-svelte-event` detector to build the liberal
348 /// "listened" set. Empty for every non-Svelte file.
349 pub svelte_listened_events: Vec<String>,
350 /// `true` when a `dispatch(<nonLiteral>)` call was seen (the dispatched event
351 /// name cannot be known statically), or the `dispatch` binding was used as a
352 /// whole value (passed / returned). The `unused-svelte-event` detector
353 /// abstains on the whole component so an event is never falsely flagged.
354 pub has_dynamic_dispatch: bool,
355}
356
357impl ModuleInfo {
358 /// A fully-zeroed `ModuleInfo` for the given file.
359 ///
360 /// Fixture builders and non-JS extraction paths start from this and set
361 /// only the fields they care about via struct-update syntax:
362 /// `ModuleInfo { exports: vec![..], ..ModuleInfo::empty(file_id) }`.
363 #[must_use]
364 pub fn empty(file_id: FileId) -> Self {
365 Self {
366 file_id,
367 exports: Arc::default(),
368 imports: Vec::new(),
369 re_exports: Vec::new(),
370 dynamic_imports: Vec::new(),
371 dynamic_import_patterns: Vec::new(),
372 require_calls: Vec::new(),
373 package_path_references: Box::default(),
374 member_accesses: Arc::default(),
375 semantic_facts: Arc::default(),
376 whole_object_uses: Arc::default(),
377 has_cjs_exports: false,
378 has_angular_component_template_url: false,
379 content_hash: 0,
380 suppressions: Vec::new(),
381 unknown_suppression_kinds: Vec::new(),
382 unused_import_bindings: Vec::new(),
383 type_referenced_import_bindings: Vec::new(),
384 value_referenced_import_bindings: Vec::new(),
385 line_offsets: Vec::new(),
386 complexity: Vec::new(),
387 flag_uses: Vec::new(),
388 class_heritage: Vec::new(),
389 exported_factory_returns: Arc::default(),
390 exported_factory_return_object_shapes: Arc::default(),
391 type_member_types: Arc::default(),
392 injection_tokens: Vec::new(),
393 local_type_declarations: Vec::new(),
394 public_signature_type_references: Vec::new(),
395 namespace_object_aliases: Vec::new(),
396 iconify_prefixes: Vec::new(),
397 iconify_icon_names: Vec::new(),
398 auto_import_candidates: Vec::new(),
399 directives: Vec::new(),
400 client_only_dynamic_import_spans: Vec::new(),
401 security_sinks: Vec::new(),
402 security_sinks_skipped: 0,
403 security_unresolved_callee_sites: Vec::new(),
404 tainted_bindings: Vec::new(),
405 sanitized_sink_args: Vec::new(),
406 security_control_sites: Vec::new(),
407 callee_uses: Vec::new(),
408 misplaced_directives: Vec::new(),
409 inline_server_action_exports: Vec::new(),
410 di_key_sites: Vec::new(),
411 has_dynamic_provide: false,
412 referenced_import_bindings: Vec::new(),
413 component_props: Vec::new(),
414 has_props_attrs_fallthrough: false,
415 has_define_expose: false,
416 has_define_model: false,
417 has_unharvestable_props: false,
418 component_emits: Vec::new(),
419 angular_inputs: Vec::new(),
420 angular_outputs: Vec::new(),
421 has_unharvestable_emits: false,
422 has_dynamic_emit: false,
423 has_emit_whole_object_use: false,
424 load_return_keys: Vec::new(),
425 has_unharvestable_load: false,
426 has_load_data_whole_use: false,
427 has_page_data_store_whole_use: false,
428 has_route_loader_data_whole_use: false,
429 component_functions: Vec::new(),
430 react_props: Vec::new(),
431 hook_uses: Vec::new(),
432 render_edges: Vec::new(),
433 svelte_dispatched_events: Vec::new(),
434 svelte_listened_events: Vec::new(),
435 angular_component_selectors: Vec::new(),
436 registered_custom_elements: Vec::new(),
437 used_custom_element_tags: Vec::new(),
438 angular_used_selectors: Vec::new(),
439 angular_entry_component_refs: Vec::new(),
440 has_dynamic_component_render: false,
441 has_dynamic_dispatch: false,
442 }
443 }
444
445 /// Derive compact detector facts from resolution payload before sharing.
446 ///
447 /// Shared analysis sessions keep the source payload for later graph runs,
448 /// but detectors still require the same derived facts that the owned
449 /// release path computes before clearing that payload.
450 #[doc(hidden)]
451 pub fn prepare_analysis_facts(&mut self) {
452 // The analyze-layer `unrendered-component` detector needs the compact
453 // complement of imports and unused bindings after resolution.
454 self.referenced_import_bindings = self
455 .imports
456 .iter()
457 .map(|import| import.local_name.clone())
458 .filter(|name| !name.is_empty() && !self.unused_import_bindings.contains(name))
459 .collect();
460 self.referenced_import_bindings.sort_unstable();
461 self.referenced_import_bindings.dedup();
462
463 // The `unused-load-data-key` detector needs the project-wide signal
464 // after `whole_object_uses` is released from owned artifacts.
465 self.has_page_data_store_whole_use = self
466 .whole_object_uses
467 .iter()
468 .any(|name| name == "page.data" || name == "$page.data");
469 self.has_route_loader_data_whole_use = self
470 .whole_object_uses
471 .iter()
472 .any(|name| name == "$fallow.routeLoaderData");
473 }
474
475 /// Release extraction payload that resolution has already copied into the graph.
476 ///
477 /// This keeps fields needed by analysis, health, security, LSP, coverage,
478 /// and hash drift checks, while dropping vectors that otherwise duplicate
479 /// data owned by `ResolvedModule` or already credited into the module graph.
480 pub fn release_resolution_payload(&mut self) {
481 self.prepare_analysis_facts();
482 Self::release_vec(&mut self.dynamic_imports);
483 Self::release_vec(&mut self.require_calls);
484 Self::release_boxed_slice(&mut self.package_path_references);
485 Self::release_arc_slice(&mut self.whole_object_uses);
486 Self::release_vec(&mut self.unused_import_bindings);
487 Self::release_vec(&mut self.type_referenced_import_bindings);
488 Self::release_vec(&mut self.value_referenced_import_bindings);
489 Self::release_vec(&mut self.namespace_object_aliases);
490 Self::release_vec(&mut self.auto_import_candidates);
491 }
492
493 fn release_vec<T>(values: &mut Vec<T>) {
494 *values = Vec::new();
495 }
496
497 fn release_boxed_slice<T>(values: &mut Box<[T]>) {
498 *values = Box::default();
499 }
500
501 /// Drop this module's refcount; the allocation itself is freed only once
502 /// the sharing `ResolvedModule` releases its clone too.
503 fn release_arc_slice<T>(values: &mut Arc<[T]>) {
504 *values = Arc::default();
505 }
506}
507
508/// Defensive control family detected on a source to sink path.
509#[derive(
510 Debug,
511 Clone,
512 Copy,
513 PartialEq,
514 Eq,
515 PartialOrd,
516 Ord,
517 serde::Serialize,
518 serde::Deserialize,
519 bitcode::Encode,
520 bitcode::Decode,
521)]
522#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
523#[serde(rename_all = "kebab-case")]
524pub enum SecurityControlKind {
525 /// Sanitization or escaping before a sink.
526 Sanitization,
527 /// Input validation or schema parsing.
528 Validation,
529 /// Authentication check or middleware.
530 Authentication,
531 /// Authorization or permission check.
532 Authorization,
533}
534
535/// A known defensive control call site.
536#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
537pub struct SecurityControlSite {
538 /// Control family.
539 pub kind: SecurityControlKind,
540 /// Flattened callee path or a stable synthetic name for guard-derived
541 /// controls.
542 pub callee_path: String,
543 /// Byte offset of the control span start.
544 pub span_start: u32,
545 /// Byte offset of the control span end.
546 pub span_end: u32,
547}
548
549/// Sanitizer output domain. Kept intentionally narrow so a sanitizer for one
550/// domain cannot suppress a different sink family.
551#[derive(
552 Debug,
553 Clone,
554 Copy,
555 PartialEq,
556 Eq,
557 PartialOrd,
558 Ord,
559 serde::Serialize,
560 serde::Deserialize,
561 bitcode::Encode,
562 bitcode::Decode,
563)]
564pub enum SanitizerScope {
565 /// HTML markup sanitized by DOMPurify-compatible APIs.
566 Html,
567 /// URL or redirect target checked against a literal-backed allowlist.
568 Url,
569 /// Path value checked against a high-confidence containment guard.
570 Path,
571 /// SQL identifier quoted with a helper that doubles embedded identifier quotes.
572 SqlIdentifier,
573}
574
575/// A captured sink argument that is itself a recognized sanitizer call.
576#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
577pub struct SanitizedSinkArg {
578 /// Byte offset of the owning sink span start.
579 pub span_start: u32,
580 /// The positional argument index on the owning sink.
581 pub arg_index: u32,
582 /// The sanitizer output domain for this argument.
583 pub scope: SanitizerScope,
584}
585
586/// A local binding tied to the flattened member-access path it was initialized
587/// from. The analyze layer matches `source_path` against the data-driven source
588/// catalogue; when it matches, `local` is treated as carrying untrusted input.
589///
590/// Captured for two shapes: a direct assignment (`const id = req.query.id` ->
591/// `{ local: "id", source_path: "req.query" }`, the literal-key tail dropped so
592/// the path matches a catalogue prefix) and an object destructure
593/// (`const { id } = req.query` -> `{ local: "id", source_path: "req.query" }`).
594#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
595pub struct TaintedBinding {
596 /// The local binding name introduced by the declarator.
597 pub local: String,
598 /// The flattened object member-access path the binding was sourced from.
599 pub source_path: String,
600 /// Byte offset of the source read (the member-access expression the binding
601 /// was sourced from), so the analyze layer can anchor a taint trace's source
602 /// node at the real read line instead of the module import line. Stored as a
603 /// `u32` (not `Span`) to stay bitcode-encodable for the cache. `0` when no
604 /// concrete read expression is available (synthetic framework-param /
605 /// helper-return bindings), in which case the analyze layer falls back to the
606 /// sink site rather than claiming a spurious line.
607 pub source_span_start: u32,
608}
609
610/// Why a sink-shaped callee could not be flattened into a static catalogue
611/// path.
612#[derive(
613 Debug,
614 Clone,
615 Copy,
616 PartialEq,
617 Eq,
618 PartialOrd,
619 Ord,
620 serde::Serialize,
621 serde::Deserialize,
622 bitcode::Encode,
623 bitcode::Decode,
624)]
625#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
626#[serde(rename_all = "kebab-case")]
627pub enum SkippedSecurityCalleeReason {
628 /// A computed member access such as `client[method](input)`.
629 ComputedMember,
630 /// A dynamic non-member callee such as `(factory())(input)`.
631 DynamicDispatch,
632 /// An assignment target whose object could not be flattened.
633 UnsupportedAssignmentObject,
634}
635
636/// Syntactic expression shape for a skipped security callee.
637#[derive(
638 Debug,
639 Clone,
640 Copy,
641 PartialEq,
642 Eq,
643 PartialOrd,
644 Ord,
645 serde::Serialize,
646 serde::Deserialize,
647 bitcode::Encode,
648 bitcode::Decode,
649)]
650#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
651#[serde(rename_all = "kebab-case")]
652pub enum SkippedSecurityCalleeExpressionKind {
653 /// `obj.prop(...)`.
654 StaticMemberExpression,
655 /// `obj[prop](...)`.
656 ComputedMemberExpression,
657 /// A bare identifier or private identifier callee.
658 Identifier,
659 /// Any other call-like expression that cannot be represented compactly.
660 Other,
661}
662
663/// Span-only diagnostic for a skipped security callee inside one module.
664#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
665pub struct SkippedSecurityCalleeSite {
666 /// Why the callee was skipped.
667 pub reason: SkippedSecurityCalleeReason,
668 /// Compact expression shape of the skipped callee.
669 pub expression_kind: SkippedSecurityCalleeExpressionKind,
670 /// Start byte offset of the skipped callee expression.
671 pub span_start: u32,
672 /// End byte offset of the skipped callee expression.
673 pub span_end: u32,
674}
675
676/// The syntactic shape of a captured security sink site. Category-blind: the
677/// extractor records the shape and the dotted/bare callee path; the analyze
678/// layer matches it against the data-driven catalogue. See
679/// `crates/security/data/security_matchers.toml`.
680#[derive(
681 Debug,
682 Clone,
683 Copy,
684 PartialEq,
685 Eq,
686 serde::Serialize,
687 serde::Deserialize,
688 bitcode::Encode,
689 bitcode::Decode,
690)]
691pub enum SinkShape {
692 /// A call to a bare identifier (e.g. `eval(x)`).
693 Call,
694 /// A call to a dotted member path (e.g. `child_process.exec(x)`).
695 MemberCall,
696 /// An assignment to a member target (e.g. `el.innerHTML = x`).
697 MemberAssign,
698 /// A tagged template expression (e.g. ``sql`...${x}...` ``).
699 TaggedTemplate,
700 /// A JSX attribute value (e.g. `dangerouslySetInnerHTML={x}`).
701 JsxAttr,
702 /// A constructor call (e.g. `new Function("return x")`).
703 NewExpression,
704 /// A static string literal assigned to a secret-shaped identifier or known
705 /// provider credential prefix.
706 SecretLiteral,
707}
708
709/// The shape of the argument captured at a sink site. Category-blind like
710/// [`SinkShape`], but finer-grained: it lets the catalogue matcher require or
711/// exclude specific argument shapes. The discriminator is what distinguishes an
712/// unsafe SQL string concatenation or template-into-`.execute()` from a
713/// safely-parameterized `` sql`${x}` `` tagged template, an object-literal
714/// `.execute({ sql, args })` argument, or a literal-aware sink argument.
715#[derive(
716 Debug,
717 Clone,
718 Copy,
719 PartialEq,
720 Eq,
721 serde::Serialize,
722 serde::Deserialize,
723 bitcode::Encode,
724 bitcode::Decode,
725)]
726pub enum SinkArgKind {
727 /// A template literal with at least one `${...}` substitution (e.g.
728 /// `` `SELECT ${x}` ``). On a `tagged-template` shape this is the tag's
729 /// quasi; on a `call`/`member-call` shape it is the positional argument.
730 TemplateWithSubst,
731 /// A binary `+` string concatenation (e.g. `"SELECT " + x`).
732 Concat,
733 /// An object literal (e.g. `.execute({ sql, args })`, the parameterized form).
734 Object,
735 /// A call expression argument (e.g. `query(buildSql())`).
736 Call,
737 /// A literal argument admitted by a literal-aware security matcher.
738 Literal,
739 /// A zero-argument sink captured because the callee itself is the signal.
740 NoArg,
741 /// Any other non-literal expression (bare identifier, member access, etc.).
742 Other,
743}
744
745/// Static URL construction shape captured for URL-shaped security sinks.
746#[derive(
747 Debug,
748 Clone,
749 Copy,
750 PartialEq,
751 Eq,
752 serde::Serialize,
753 serde::Deserialize,
754 bitcode::Encode,
755 bitcode::Decode,
756)]
757#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
758#[serde(rename_all = "kebab-case")]
759pub enum SecurityUrlShape {
760 /// The sink target has a fixed origin, scheme, or relative root while only
761 /// path or query components are dynamic.
762 FixedOriginDynamicPath,
763 /// The sink target's scheme or origin is dynamic or opaque.
764 DynamicOrigin,
765}
766
767/// Literal values attached to literal-aware security sink captures.
768#[derive(
769 Debug,
770 Clone,
771 PartialEq,
772 Eq,
773 serde::Serialize,
774 serde::Deserialize,
775 bitcode::Encode,
776 bitcode::Decode,
777)]
778pub enum SinkLiteralValue {
779 /// A string literal value.
780 String(String),
781 /// An integer numeric literal value.
782 Integer(i64),
783 /// A boolean literal value.
784 Boolean(bool),
785 /// A null literal value.
786 Null,
787}
788
789/// Static object-literal property metadata attached to a captured sink
790/// argument. Nested object paths are flattened with dot-separated keys.
791#[derive(
792 Debug,
793 Clone,
794 PartialEq,
795 Eq,
796 serde::Serialize,
797 serde::Deserialize,
798 bitcode::Encode,
799 bitcode::Decode,
800)]
801pub struct SinkObjectProperty {
802 /// Static property name. Nested object properties use dot-separated paths.
803 pub key: String,
804 /// Literal property value when statically knowable.
805 pub value: SinkLiteralValue,
806}
807
808/// A captured sink site. The visitor records every existing non-literal call /
809/// member-assign / member-call / tagged-template / jsx-attr sink site, and a
810/// small allowlist of literal-aware sites where the literal value is the signal.
811/// It knows nothing about CWE categories.
812#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
813pub struct SinkSite {
814 /// The syntactic shape of the sink site.
815 pub sink_shape: SinkShape,
816 /// The flattened dotted/bare callee or member path.
817 pub callee_path: String,
818 /// The positional argument index. For zero-argument captures this is 0.
819 pub arg_index: u32,
820 /// Whether the relevant argument is non-literal. Existing non-literal
821 /// catalogue rows require this to remain true.
822 pub arg_is_non_literal: bool,
823 /// The finer-grained shape of the captured argument. Lets the catalogue
824 /// require unsafe shapes (concat / template-with-substitution / literal /
825 /// no-arg) and exclude safe ones (object literal, the parameterized form).
826 /// See [`SinkArgKind`].
827 pub arg_kind: SinkArgKind,
828 /// Literal argument value for literal-aware rows.
829 pub arg_literal: Option<SinkLiteralValue>,
830 /// Risky regex fragment for structural ReDoS candidates.
831 pub regex_pattern: Option<String>,
832 /// Static object-literal properties for option-object rows.
833 pub object_properties: Vec<SinkObjectProperty>,
834 /// Static top-level object-literal keys, including keys whose values are not
835 /// literal. Used by missing-option rows that only need key presence.
836 pub object_property_keys: Vec<String>,
837 /// Whether [`object_property_keys`](Self::object_property_keys) is complete.
838 /// False for non-object arguments and object literals with spread or
839 /// non-static keys, where a missing-key claim would be speculative.
840 pub object_property_keys_complete: bool,
841 /// Identifier names referenced anywhere inside the captured non-literal sink
842 /// argument, or contextual names for zero-argument captures such as a
843 /// token-like `Math.random()` assignment target. Deduped in source order.
844 /// Used by the analyze layer to back-trace the sink argument to a known
845 /// untrusted source or to apply narrow context gates. Intra-module,
846 /// name-based, conservative; it is never a taint proof.
847 pub arg_idents: Vec<String>,
848 /// Flattened static member paths referenced inside the captured non-literal
849 /// sink argument. Includes both the full path and source-object path for
850 /// leaf reads (`process.env.SECRET` records `process.env.SECRET` and
851 /// `process.env`) so direct source expressions can be matched without an
852 /// intermediate local binding.
853 pub arg_source_paths: Vec<String>,
854 /// Byte offset of the sink span start. Stored as `u32` (not `Span`) so the
855 /// struct is bitcode-encodable and can be persisted directly in the cache.
856 pub span_start: u32,
857 /// Byte offset of the sink span end.
858 pub span_end: u32,
859 /// The arg-0 URL string literal of a network-shaped call (`fetch`, `axios.*`,
860 /// `got`, ...), captured so the `secret-to-network` category (#890) can carry
861 /// a destination-host signal on its candidate: `Some(literal)` when the
862 /// destination is a static string literal (almost always intended auth, e.g.
863 /// the credential's own provider), `None` when it is dynamic (the suspicious
864 /// case). `None` for non-call sinks and calls with no arg 0.
865 pub url_arg_literal: Option<String>,
866 /// URL construction shape for URL-like sink arguments when the extractor can
867 /// classify it syntactically. `None` for non-URL sinks and URL expressions
868 /// whose shape is not visible at the sink.
869 pub url_shape: Option<SecurityUrlShape>,
870}
871
872impl SinkSite {
873 /// Reconstruct the source span from the stored byte offsets.
874 #[must_use]
875 pub fn span(&self) -> Span {
876 Span::new(self.span_start, self.span_end)
877 }
878}
879
880/// Env var-name prefixes that frameworks inline into the client bundle by
881/// convention. A read of one of these is normal and safe, so it does NOT count
882/// as a secret source (issue #890). Shared by the extract layer (so public env
883/// vars never become source signals) and the bespoke `client-server-leak` rule.
884pub const PUBLIC_ENV_PREFIXES: &[&str] = &[
885 "NEXT_PUBLIC_",
886 "VITE_",
887 "NUXT_PUBLIC_",
888 "REACT_APP_",
889 "PUBLIC_",
890 "GATSBY_",
891 "EXPO_PUBLIC_",
892 "STORYBOOK_",
893];
894
895/// Exact env var names that are public by convention (no prefix).
896pub const PUBLIC_ENV_EXACT: &[&str] = &["NODE_ENV"];
897
898/// Env var-name tokens that usually describe public build or deployment
899/// metadata rather than secrets. Secret-shaped names win over these tokens.
900pub const PUBLIC_ENV_METADATA_TOKENS: &[&str] =
901 &["BRANCH", "ENVIRONMENT", "MODE", "REF", "SHA", "TAG"];
902
903/// Env var-name tokens that should keep a variable source-backed even when the
904/// name also contains public metadata tokens such as `REF` or `SHA`.
905pub const SECRET_ENV_TOKENS: &[&str] = &[
906 "AUTH",
907 "CREDENTIAL",
908 "CREDENTIALS",
909 "KEY",
910 "PASS",
911 "PASSWORD",
912 "PRIVATE",
913 "SECRET",
914 "TOKEN",
915];
916
917fn env_name_has_token(name: &str, tokens: &[&str]) -> bool {
918 name.split(|ch: char| !ch.is_ascii_alphanumeric())
919 .filter(|part| !part.is_empty())
920 .any(|part| tokens.contains(&part))
921}
922
923/// Whether an env var name is public-by-convention (build-inlined into the
924/// client bundle), and therefore not a secret.
925#[must_use]
926pub fn is_public_env_var(name: &str) -> bool {
927 if PUBLIC_ENV_EXACT.contains(&name) || PUBLIC_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) {
928 return true;
929 }
930 env_name_has_token(name, PUBLIC_ENV_METADATA_TOKENS)
931 && !env_name_has_token(name, SECRET_ENV_TOKENS)
932}
933
934/// Whether a flattened member path is a PUBLIC env-secret read
935/// (`process.env.NEXT_PUBLIC_X`, `import.meta.env.VITE_Y`), which must not be
936/// recorded as a secret source. Non-env paths (`req.query.id`) are never public.
937#[must_use]
938pub fn is_public_env_path(path: &str) -> bool {
939 for object in ["process.env.", "import.meta.env."] {
940 if let Some(var) = path.strip_prefix(object) {
941 return is_public_env_var(var);
942 }
943 }
944 false
945}
946
947/// One alias entry tying an exported object's dotted property path to a namespace import.
948#[derive(Debug, Clone)]
949pub struct NamespaceObjectAlias {
950 /// Canonical export name.
951 pub via_export_name: String,
952 /// Dotted suffix of the property path relative to the export.
953 pub suffix: String,
954 /// Local name of the namespace import.
955 pub namespace_local: String,
956}
957
958/// Compute a table of line-start byte offsets from source text.
959#[must_use]
960#[expect(
961 clippy::cast_possible_truncation,
962 reason = "source files are practically < 4GB"
963)]
964pub fn compute_line_offsets(source: &str) -> Vec<u32> {
965 let mut offsets = vec![0u32];
966 for (i, byte) in source.bytes().enumerate() {
967 if byte == b'\n' {
968 debug_assert!(
969 u32::try_from(i + 1).is_ok(),
970 "source file exceeds u32::MAX bytes: line offsets would overflow"
971 );
972 offsets.push((i + 1) as u32);
973 }
974 }
975 offsets
976}
977
978/// Convert a byte offset to a 1-based line number and 0-based byte column.
979#[must_use]
980#[expect(
981 clippy::cast_possible_truncation,
982 reason = "line count is bounded by source size"
983)]
984pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
985 let line_idx = match line_offsets.binary_search(&byte_offset) {
986 Ok(idx) => idx,
987 Err(idx) => idx.saturating_sub(1),
988 };
989 let line = line_idx as u32 + 1;
990 let col = byte_offset - line_offsets[line_idx];
991 (line, col)
992}
993
994/// True when `name` identifies a synthetic template-family complexity unit:
995/// the per-file `<template>` unit every framework template scanner emits, or a
996/// Svelte `<snippet:NAME>` unit. These units are exercised only through their
997/// component, carry no directly measurable test coverage, and are therefore
998/// excluded from the CRAP dimension. The `<component>` rollup is NOT part of
999/// this family: it is an aggregate over class + template findings, not an
1000/// extracted unit.
1001#[must_use]
1002pub fn is_synthetic_template_unit(name: &str) -> bool {
1003 name == "<template>" || name.starts_with("<snippet:")
1004}
1005
1006/// Complexity metrics for a single function/method/arrow.
1007#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1008pub struct FunctionComplexity {
1009 /// Function name (or `"<anonymous>"` for unnamed functions/arrows).
1010 pub name: String,
1011 /// Whether this function is an ECMAScript `#`-private class member.
1012 ///
1013 /// Kept separately from `name` because a public string-named method may
1014 /// legally begin with `#` and remains eligible for runtime coverage.
1015 pub is_private_member: bool,
1016 /// 1-based line number where the function starts.
1017 pub line: u32,
1018 /// 0-based byte column where the function starts.
1019 pub col: u32,
1020 /// `McCabe` cyclomatic complexity (1 + decision points).
1021 pub cyclomatic: u16,
1022 /// `SonarSource` cognitive complexity (structural + nesting penalty).
1023 pub cognitive: u16,
1024 /// Number of lines in the function body.
1025 pub line_count: u32,
1026 /// Number of parameters (excluding TypeScript's `this` parameter).
1027 pub param_count: u8,
1028 /// Number of React hook calls (`useState` / `useEffect` / `useMemo` /
1029 /// `useCallback` / custom `use*`) made directly in this function's body.
1030 /// Non-zero only for React components/hooks; descriptive context surfaced in
1031 /// the hotspot drill-down, never a tunable threshold (anti-numerology).
1032 pub react_hook_count: u16,
1033 /// Maximum JSX element nesting depth reached in this function's body (the
1034 /// deepest chain of element-inside-element). `0` when the function renders
1035 /// no JSX. Descriptive context surfaced in the hotspot drill-down, never a
1036 /// tunable threshold (anti-numerology).
1037 pub react_jsx_max_depth: u16,
1038 /// Number of props destructured from this component's first parameter (the
1039 /// `{ a, b, c }` props object). `0` for non-component functions and for
1040 /// components taking a bare `props` identifier (not statically countable).
1041 /// Descriptive context surfaced in the hotspot drill-down, never a tunable
1042 /// threshold (anti-numerology).
1043 pub react_prop_count: u16,
1044 /// Content digest of the function's full-span source slice.
1045 pub source_hash: Option<String>,
1046 /// Per-decision-point breakdown explaining WHICH constructs drove the
1047 /// cyclomatic and cognitive scores. One entry per increment event (an `if`
1048 /// emits one cyclomatic and one cognitive entry at the same line, because
1049 /// the two metrics accrue at different granularities). Always computed and
1050 /// cached; surfaced in JSON only behind `health --complexity-breakdown`.
1051 pub contributions: Vec<ComplexityContribution>,
1052}
1053
1054/// Structural CSS metrics for a single style rule, computed from the parsed CSS
1055/// syntax tree. A rule is recorded only when it crosses a structural floor (an
1056/// id selector, a complex selector, a `!important` declaration, or deep
1057/// nesting), so the vector stays bounded on normal stylesheets.
1058///
1059/// Not persisted in the extraction cache: `fallow health` computes these
1060/// on demand from the CSS source, so there is no `bitcode` derive.
1061#[derive(Debug, Clone, serde::Serialize)]
1062#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1063pub struct CssRuleMetric {
1064 /// 1-based line of the rule's first selector.
1065 pub line: u32,
1066 /// 1-based column of the rule's first selector.
1067 pub col: u32,
1068 /// Specificity component `a` (id selectors), max across the rule's selectors.
1069 pub specificity_a: u16,
1070 /// Specificity component `b` (class / attribute / pseudo-class selectors).
1071 pub specificity_b: u16,
1072 /// Specificity component `c` (type / pseudo-element selectors).
1073 pub specificity_c: u16,
1074 /// Largest selector component count across the rule's selector list.
1075 pub complexity: u16,
1076 /// Declaration count in the rule (normal plus `!important`).
1077 pub declaration_count: u16,
1078 /// `!important` declaration count in the rule.
1079 pub important_count: u16,
1080 /// Style-rule nesting depth (0 = top level).
1081 pub nesting_depth: u8,
1082}
1083
1084/// A style rule's declaration-block fingerprint and location, for cross-file
1085/// duplicate-block detection. Only rules with a meaningful number of
1086/// declarations are recorded (small blocks repeat legitimately). Internal
1087/// staging only: this is consumed in-process by the health layer to build the
1088/// grouped `duplicate_declaration_blocks` output and is never serialized.
1089#[derive(Debug, Clone)]
1090pub struct CssDeclarationBlock {
1091 /// xxh3 fingerprint over the rule's normalized (sorted, `!important`-tagged)
1092 /// declaration set.
1093 pub fingerprint: u64,
1094 /// 1-based line of the rule's first selector.
1095 pub line: u32,
1096 /// Declaration count in the rule (normal plus `!important`).
1097 pub declaration_count: u16,
1098}
1099
1100/// Located raw styling value authored directly in CSS rather than via a
1101/// custom property or design-token helper. Internal staging for the health
1102/// layer; public output adds actions and confidence.
1103#[derive(Debug, Clone, PartialEq, Eq)]
1104pub struct CssRawStyleValue {
1105 /// Value axis, e.g. `color`, `font-size`, `line-height`, `radius`, or `shadow`.
1106 pub axis: String,
1107 /// CSS property where the value appears.
1108 pub property: String,
1109 /// Rendered declaration value.
1110 pub value: String,
1111 /// 1-based line of the containing style rule.
1112 pub line: u32,
1113}
1114
1115/// Located CSS custom-property definition with its rendered value. Internal
1116/// staging for design-token reuse suggestions in the health layer.
1117#[derive(Debug, Clone, PartialEq, Eq)]
1118pub struct CssCustomPropertyDefinition {
1119 /// Custom property name, including the leading `--`.
1120 pub name: String,
1121 /// Rendered custom property value.
1122 pub value: String,
1123 /// 1-based line of the containing style rule.
1124 pub line: u32,
1125}
1126
1127/// Stylesheet-level structural CSS analytics, computed from the parsed CSS
1128/// syntax tree. Feeds `fallow health` penalty weights and located findings,
1129/// never a standalone CSS score.
1130#[derive(Debug, Clone, Default, serde::Serialize)]
1131#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1132pub struct CssAnalytics {
1133 /// Total declarations across every style rule (normal plus `!important`).
1134 pub total_declarations: u32,
1135 /// Total `!important` declarations across every style rule.
1136 pub important_declarations: u32,
1137 /// Number of style rules.
1138 pub rule_count: u32,
1139 /// Number of style rules with no declarations.
1140 pub empty_rule_count: u32,
1141 /// Deepest style-rule nesting depth observed (0 = no nesting).
1142 pub max_nesting_depth: u8,
1143 /// Rules that crossed the structural floor, in source order. Bounded; see
1144 /// [`Self::notable_truncated`]. The scalar aggregates above always reflect
1145 /// the full stylesheet regardless of truncation.
1146 pub notable_rules: Vec<CssRuleMetric>,
1147 /// `true` when more rules crossed the structural floor than `notable_rules`
1148 /// retains (compiled utility CSS can emit thousands of `!important` rules),
1149 /// so consumers can note that per-rule findings were capped.
1150 pub notable_truncated: bool,
1151 /// Distinct color VALUES in the stylesheet, sorted (a palette-size /
1152 /// design-token-sprawl signal). The parser canonicalizes notation, so the
1153 /// authored format is NOT preserved: `red`, `#f00`, `#ff0000`, and
1154 /// `rgb(255,0,0)` all collapse to one entry, and every legacy sRGB notation
1155 /// renders as hex. Notation-MIXING (hex vs rgb vs hsl) is therefore not
1156 /// detectable from this set; it would need a separate raw-token pass.
1157 pub colors: Vec<String>,
1158 /// Distinct `font-size` declaration values in the stylesheet, sorted.
1159 pub font_sizes: Vec<String>,
1160 /// Distinct `z-index` declaration values in the stylesheet, sorted.
1161 pub z_indexes: Vec<String>,
1162 /// Distinct `box-shadow` declaration values in the stylesheet, sorted. A
1163 /// high count signals an uncontrolled shadow scale (design-token sprawl).
1164 pub box_shadows: Vec<String>,
1165 /// Distinct `border-radius` declaration values in the stylesheet, sorted.
1166 pub border_radii: Vec<String>,
1167 /// Distinct `line-height` declaration values in the stylesheet, sorted.
1168 pub line_heights: Vec<String>,
1169 /// Bounded located raw styling values that bypass custom properties or
1170 /// token helpers. These are conservative declaration-level candidates for
1171 /// audit introduced-vs-base gating.
1172 #[serde(skip)]
1173 #[cfg_attr(feature = "schema", schemars(skip))]
1174 pub raw_style_values: Vec<CssRawStyleValue>,
1175 /// Located custom-property definitions with values. Internal staging
1176 /// consumed by the health layer for nearest-token suggestions.
1177 #[serde(skip)]
1178 #[cfg_attr(feature = "schema", schemars(skip))]
1179 pub custom_property_definitions: Vec<CssCustomPropertyDefinition>,
1180 /// Distinct custom properties (`--x`) DEFINED in the stylesheet, sorted.
1181 pub defined_custom_properties: Vec<String>,
1182 /// Distinct custom properties REFERENCED via `var()` in the stylesheet.
1183 pub referenced_custom_properties: Vec<String>,
1184 /// Distinct `@keyframes` names DEFINED in the stylesheet, sorted.
1185 pub defined_keyframes: Vec<String>,
1186 /// Distinct `@keyframes` names REFERENCED via `animation` / `animation-name`.
1187 pub referenced_keyframes: Vec<String>,
1188 /// Distinct custom properties REGISTERED via an `@property` rule, sorted.
1189 pub registered_custom_properties: Vec<String>,
1190 /// Distinct cascade layers DECLARED (via `@layer a, b;` statements or named
1191 /// `@layer a { }` blocks), sorted.
1192 pub declared_layers: Vec<String>,
1193 /// Distinct cascade layers POPULATED by a named `@layer a { }` block, sorted.
1194 /// A layer declared but never populated (and not imported into) is a
1195 /// cleanup candidate.
1196 pub populated_layers: Vec<String>,
1197 /// Distinct font families DECLARED by an `@font-face` rule in the stylesheet,
1198 /// sorted. A declared family referenced by no `font-family` anywhere is a
1199 /// dead web-font payload (cleanup candidate).
1200 pub defined_font_faces: Vec<String>,
1201 /// Distinct font families REFERENCED via `font-family` / `font` in the
1202 /// stylesheet, sorted (generic keywords like `serif` excluded).
1203 pub referenced_font_families: Vec<String>,
1204 /// Per-rule declaration-block fingerprints for rules at or above the minimum
1205 /// block size, used to detect duplicate declaration blocks across the
1206 /// project. Internal staging consumed by the health layer; never serialized
1207 /// (the public output is the grouped `duplicate_declaration_blocks`).
1208 #[serde(skip)]
1209 #[cfg_attr(feature = "schema", schemars(skip))]
1210 pub declaration_blocks: Vec<CssDeclarationBlock>,
1211}
1212
1213/// Which complexity metric a [`ComplexityContribution`] adds to.
1214#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1215#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1216#[serde(rename_all = "kebab-case")]
1217pub enum ComplexityMetric {
1218 /// `McCabe` cyclomatic complexity (independent execution paths).
1219 Cyclomatic,
1220 /// `SonarSource` cognitive complexity (structural + nesting penalty).
1221 Cognitive,
1222}
1223
1224/// The syntactic construct that produced a single complexity increment.
1225///
1226/// Mirrors `SonarSource` cognitive-complexity vocabulary where it overlaps.
1227/// `Case` means a `case` label carrying a test; a bare `default` adds nothing
1228/// to cyclomatic complexity and so produces no contribution.
1229#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1230#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1231#[serde(rename_all = "kebab-case")]
1232#[non_exhaustive]
1233pub enum ComplexityContributionKind {
1234 /// An `if` condition.
1235 If,
1236 /// A bare `else` branch (cognitive only).
1237 Else,
1238 /// An `else if` continuation (both metrics: cyclomatic +1, cognitive flat
1239 /// +1 with no nesting penalty).
1240 ElseIf,
1241 /// A `?:` conditional (ternary) expression.
1242 Ternary,
1243 /// A logical `&&` operator.
1244 LogicalAnd,
1245 /// A logical `||` operator.
1246 LogicalOr,
1247 /// A `??` nullish-coalescing operator.
1248 NullishCoalescing,
1249 /// A logical assignment operator (`&&=`, `||=`, `??=`); cyclomatic only.
1250 LogicalAssignment,
1251 /// An optional-chaining link (`?.`); cyclomatic only.
1252 OptionalChain,
1253 /// A `for` loop.
1254 For,
1255 /// A `for...in` loop.
1256 ForIn,
1257 /// A `for...of` loop.
1258 ForOf,
1259 /// A `while` loop.
1260 While,
1261 /// A `do...while` loop.
1262 DoWhile,
1263 /// A `switch` statement (cognitive only; each `case` adds cyclomatic).
1264 Switch,
1265 /// A `case` label carrying a test (cyclomatic only).
1266 Case,
1267 /// A `catch` clause.
1268 Catch,
1269 /// A labeled `break` (cognitive only).
1270 LabeledBreak,
1271 /// A labeled `continue` (cognitive only).
1272 LabeledContinue,
1273 /// Legacy JSX-depth contribution kind kept for schema compatibility. Current
1274 /// extraction records JSX nesting as descriptive `react_jsx_max_depth`
1275 /// context and does not emit this kind for layout depth.
1276 JsxDepth,
1277 /// React hook density (cognitive only). One contribution per hook call in a
1278 /// component body (`useState` / `useEffect` / `useMemo` / `useCallback` /
1279 /// custom `use*`); a hook-heavy component accrues cognitive load the same way
1280 /// branching does.
1281 HookDensity,
1282 /// React prop count past the comfortable floor (cognitive only). A component
1283 /// destructuring many props is doing many things; the props beyond the floor
1284 /// fold into cognitive so a wide-interface component surfaces as a hotspot.
1285 PropCount,
1286 /// A Svelte `{#await}` block.
1287 Await,
1288 /// A Svelte `{:then}` continuation.
1289 Then,
1290}
1291
1292/// A single complexity increment, located at its source line/column.
1293///
1294/// `weight` is the amount this construct added to `metric`; for nested
1295/// cognitive increments `weight == 1 + nesting`. Consumers that render inline
1296/// (the VS Code editor breakdown) group contributions by `line` and sum the
1297/// weights, deferring the per-kind list to a hover.
1298#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1299#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1300pub struct ComplexityContribution {
1301 /// 1-based line number where the construct begins.
1302 pub line: u32,
1303 /// 0-based byte column where the construct begins.
1304 pub col: u32,
1305 /// Which metric this increment contributes to.
1306 pub metric: ComplexityMetric,
1307 /// The syntactic construct responsible for the increment.
1308 pub kind: ComplexityContributionKind,
1309 /// The amount added to `metric` at this site (`1 + nesting` for nested
1310 /// cognitive increments, otherwise `1`).
1311 pub weight: u16,
1312 /// The nesting depth at the increment site (`0` when not nested). Lets a
1313 /// consumer explain a cognitive `+3` as "+1 base, +2 nesting".
1314 pub nesting: u16,
1315}
1316
1317/// The kind of feature flag pattern detected.
1318#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1319pub enum FlagUseKind {
1320 /// `process.env.FEATURE_X` pattern.
1321 EnvVar,
1322 /// SDK function call like `useFlag('name')`.
1323 SdkCall,
1324 /// Config object access like `config.features.x`.
1325 ConfigObject,
1326}
1327
1328/// A feature flag use site.
1329#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
1330pub struct FlagUse {
1331 /// Flag identifier.
1332 pub flag_name: String,
1333 /// Detection kind.
1334 pub kind: FlagUseKind,
1335 /// 1-based line number.
1336 pub line: u32,
1337 /// 0-based byte column offset.
1338 pub col: u32,
1339 /// Start byte offset of the guarded block.
1340 pub guard_span_start: Option<u32>,
1341 /// End byte offset of the guarded block.
1342 pub guard_span_end: Option<u32>,
1343 /// SDK/provider name.
1344 pub sdk_name: Option<String>,
1345}
1346
1347const _: () = assert!(std::mem::size_of::<FlagUse>() <= 96);
1348
1349/// The runtime mechanism used to load a module.
1350#[derive(
1351 Debug,
1352 Clone,
1353 Copy,
1354 PartialEq,
1355 Eq,
1356 Hash,
1357 serde::Serialize,
1358 serde::Deserialize,
1359 bitcode::Encode,
1360 bitcode::Decode,
1361)]
1362#[repr(u8)]
1363pub enum ModuleLoadMechanism {
1364 /// ECMAScript module loading through imports, re-exports, or import globs.
1365 EsModule = 0,
1366 /// CommonJS module loading through `require()` or `require.context`.
1367 CommonJsRequire = 1,
1368}
1369
1370/// A dynamic import with a partially resolved pattern.
1371#[derive(Debug, Clone)]
1372pub struct DynamicImportPattern {
1373 /// Static prefix of the import path (e.g., "./locales/"). May contain glob characters.
1374 pub prefix: String,
1375 /// Static suffix of the import path (e.g., ".json"), if any.
1376 pub suffix: Option<String>,
1377 /// Source span in the original file.
1378 pub span: Span,
1379 /// Runtime mechanism used to load modules matching this pattern.
1380 pub mechanism: ModuleLoadMechanism,
1381}
1382
1383/// Visibility tag from JSDoc/TSDoc comments that suppresses unused-export detection.
1384#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1385#[serde(rename_all = "lowercase")]
1386#[repr(u8)]
1387pub enum VisibilityTag {
1388 /// No visibility tag present.
1389 #[default]
1390 None = 0,
1391 /// `@public` or `@api public` -- part of the public API surface.
1392 Public = 1,
1393 /// `@internal` -- exported for internal use (sister packages, build tools).
1394 Internal = 2,
1395 /// `@beta` -- public but unstable, may change without notice.
1396 Beta = 3,
1397 /// `@alpha` -- early preview, may change drastically without notice.
1398 Alpha = 4,
1399 /// `@expected-unused` -- intentionally unused, should warn when it becomes used.
1400 ExpectedUnused = 5,
1401}
1402
1403impl VisibilityTag {
1404 /// Whether this tag permanently suppresses unused-export detection.
1405 /// `ExpectedUnused` is handled separately (conditionally suppresses,
1406 /// reports stale when the export becomes used).
1407 pub const fn suppresses_unused(self) -> bool {
1408 matches!(
1409 self,
1410 Self::Public | Self::Internal | Self::Beta | Self::Alpha
1411 )
1412 }
1413
1414 /// For serde `skip_serializing_if`.
1415 pub fn is_none(&self) -> bool {
1416 matches!(self, Self::None)
1417 }
1418}
1419
1420/// An export declaration.
1421#[derive(Debug, Clone, serde::Serialize)]
1422pub struct ExportInfo {
1423 /// The exported name (named or default).
1424 pub name: ExportName,
1425 /// The local binding name, if different from the exported name.
1426 pub local_name: Option<String>,
1427 /// Whether this is a type-only export (`export type`).
1428 pub is_type_only: bool,
1429 /// Whether this export is registered through a runtime side effect at module load time.
1430 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1431 pub is_side_effect_used: bool,
1432 /// Visibility tag from JSDoc/TSDoc comment.
1433 #[serde(default, skip_serializing_if = "VisibilityTag::is_none")]
1434 pub visibility: VisibilityTag,
1435 /// Human-authored reason on `@expected-unused -- <reason>`, when present.
1436 #[serde(default, skip_serializing_if = "Option::is_none")]
1437 pub expected_unused_reason: Option<String>,
1438 /// Source span of the export declaration.
1439 #[serde(serialize_with = "serialize_span")]
1440 pub span: Span,
1441 /// Members of this export (for enums, classes, and namespaces).
1442 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1443 pub members: Vec<MemberInfo>,
1444 /// The local name of the parent class from `extends` clause, if any.
1445 #[serde(default, skip_serializing_if = "Option::is_none")]
1446 pub super_class: Option<String>,
1447}
1448
1449/// Additional heritage metadata for an exported class.
1450#[derive(
1451 Debug,
1452 Clone,
1453 serde::Serialize,
1454 serde::Deserialize,
1455 bitcode::Encode,
1456 bitcode::Decode,
1457 PartialEq,
1458 Eq,
1459)]
1460pub struct ClassHeritageInfo {
1461 /// Export name (`default` for default-exported classes).
1462 pub export_name: String,
1463 /// Parent class name from the `extends` clause, if any.
1464 pub super_class: Option<String>,
1465 /// Interface names from the class `implements` clause.
1466 pub implements: Vec<String>,
1467 /// Ordered class type-parameter names used to compose concrete arguments
1468 /// through multi-hop inheritance.
1469 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1470 pub type_parameters: Vec<String>,
1471 /// Typed instance bindings used to resolve member-access chains in external templates.
1472 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1473 pub instance_bindings: Vec<(String, String)>,
1474 /// Positional type arguments on the `extends` clause (the `<DerivedClient>`
1475 /// in `extends BaseService<DerivedClient>`); an empty string marks a
1476 /// positional arg that is not a plain type reference. Lets the analyze layer
1477 /// substitute a base class's generic instance-binding field type with the
1478 /// subclass's concrete type argument (issue #1910).
1479 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1480 pub super_class_type_args: Vec<String>,
1481 /// Instance-binding fields whose annotation is exactly a class type
1482 /// parameter, as `(field_name, type_param_index)`. Lets an inherited generic
1483 /// property resolve to the subclass's concrete type argument rather than the
1484 /// constraint (issue #1910).
1485 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1486 pub generic_instance_bindings: Vec<(String, usize)>,
1487}
1488
1489/// An exported free-function factory proven to return one class instance.
1490///
1491/// `export function useApi() { return new RESTApi() }` records
1492/// `FactoryReturnExport { export_name: "useApi", class_local_name: "RESTApi" }`.
1493/// The `class_local_name` is the factory module's own LOCAL name, resolved at
1494/// analyze time through that module's imports/exports to the real class export,
1495/// so a cross-module `const x = useApi(); x.member` consumer credits the class
1496/// across the boundary. See issue #1441 (Part A).
1497#[derive(
1498 Debug,
1499 Clone,
1500 serde::Serialize,
1501 serde::Deserialize,
1502 bitcode::Encode,
1503 bitcode::Decode,
1504 PartialEq,
1505 Eq,
1506)]
1507pub struct FactoryReturnExport {
1508 /// Public export name (honors `export { useApi as useRestApi }`).
1509 pub export_name: String,
1510 /// The returned class's local name within the factory module.
1511 pub class_local_name: String,
1512}
1513
1514/// One resolved property of an object-literal factory return: a dotted property
1515/// path mapped to the class the value at that path is an instance of.
1516///
1517/// `return { invoke: { orders: factory.ordersPage } }` records
1518/// `{ property_path: "invoke.orders", class_local_name: "OrdersPage" }`. The class
1519/// name is the factory module's own LOCAL name, resolved at analyze time through the
1520/// factory module's imports to the real class export. See issue #1858.
1521#[derive(
1522 Debug,
1523 Clone,
1524 serde::Serialize,
1525 serde::Deserialize,
1526 bitcode::Encode,
1527 bitcode::Decode,
1528 PartialEq,
1529 Eq,
1530)]
1531pub struct FactoryReturnObjectProperty {
1532 /// Dotted property path from the returned object literal (`orders`, `invoke.orders`).
1533 pub property_path: String,
1534 /// The property value's class local name within the factory module.
1535 pub class_local_name: String,
1536}
1537
1538/// An exported factory function that returns an object literal whose property
1539/// values are class instances, joined to its public export name.
1540///
1541/// A cross-module `const ui = createUi(); ui.orders.member` consumer emits a
1542/// `FactoryReturnObjectPropertyAccess` fact; the analyze layer resolves `export_name`
1543/// through the consumer's imports to this module, matches `property_path`, and credits
1544/// `member` on the resolved class (gated on it being a class with members). See issue #1858.
1545#[derive(
1546 Debug,
1547 Clone,
1548 serde::Serialize,
1549 serde::Deserialize,
1550 bitcode::Encode,
1551 bitcode::Decode,
1552 PartialEq,
1553 Eq,
1554)]
1555pub struct FactoryReturnObjectShapeExport {
1556 /// Public export name (honors `export { createUi as createOrdersUi }`).
1557 pub export_name: String,
1558 /// Resolved `(property_path -> class_local_name)` entries for the returned literal.
1559 pub properties: Box<[FactoryReturnObjectProperty]>,
1560}
1561
1562/// A named-type property whose declared type is a named type reference.
1563///
1564/// `interface Opts { c: OptDep }` (or `type Opts = { c: OptDep }`) records
1565/// `TypeMemberTypeEntry { type_name: "Opts", property: "c", property_type: "OptDep" }`.
1566/// Both `type_name` and `property_type` are the DECLARING module's own local
1567/// names; resolution through that module's imports/exports is deferred to
1568/// analyze time, mirroring `FactoryReturnExport.class_local_name`. Consumed by
1569/// the `unused-class-member` typed-property-hop join so a consumer's
1570/// `this.opts.c.optM()` credits `OptDep.optM` across module boundaries.
1571/// See issue #1785.
1572#[derive(
1573 Debug,
1574 Clone,
1575 serde::Serialize,
1576 serde::Deserialize,
1577 bitcode::Encode,
1578 bitcode::Decode,
1579 PartialEq,
1580 Eq,
1581)]
1582pub struct TypeMemberTypeEntry {
1583 /// Local interface or type-alias name declaring the property.
1584 pub type_name: String,
1585 /// Property name declared on the type.
1586 pub property: String,
1587 /// The property's declared type name (local to the declaring module).
1588 pub property_type: String,
1589}
1590
1591/// A module-scope declaration that can be used as a TypeScript type.
1592#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1593pub struct LocalTypeDeclaration {
1594 /// Local declaration name.
1595 pub name: String,
1596 /// Declaration identifier span.
1597 #[serde(serialize_with = "serialize_span")]
1598 pub span: Span,
1599}
1600
1601/// A reference from an exported symbol's public signature to a type name.
1602#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1603pub struct PublicSignatureTypeReference {
1604 /// Exported symbol whose signature contains the reference.
1605 pub export_name: String,
1606 /// Referenced type name. Qualified names are reduced to their root identifier.
1607 pub type_name: String,
1608 /// Reference span.
1609 #[serde(serialize_with = "serialize_span")]
1610 pub span: Span,
1611}
1612
1613/// A member of an enum, class, or namespace.
1614#[derive(Debug, Clone, serde::Serialize)]
1615pub struct MemberInfo {
1616 /// Member name.
1617 pub name: String,
1618 /// The kind of member (enum, class method/property, or namespace member).
1619 pub kind: MemberKind,
1620 /// Source span of the member declaration.
1621 #[serde(serialize_with = "serialize_span")]
1622 pub span: Span,
1623 /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
1624 /// Decorated members are used by frameworks at runtime and should not be
1625 /// flagged as unused class members, unless every decorator on the member
1626 /// is opted out via `FallowConfig.ignore_decorators`.
1627 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1628 pub has_decorator: bool,
1629 /// Full dotted path of each decorator on this member, in source order.
1630 /// `@step("x")` stores `"step"`; `@ns.foo` stores `"ns.foo"`. Empty for
1631 /// undecorated members, Angular signal-initializer properties (which set
1632 /// `has_decorator` without a literal decorator AST node), and decorators
1633 /// whose expression is not an identifier ladder (the entry is the empty
1634 /// string in that case, treated as never-matching by the predicate).
1635 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1636 pub decorator_names: Vec<String>,
1637 /// True when this is a static class method that returns a fresh instance
1638 /// of the same class: either via `return new this()` / `return new
1639 /// <SameClassName>()` in the body's last statement, or via a declared
1640 /// return type matching the class name. Consumers calling such a static
1641 /// method receive an instance, so the call result's member accesses are
1642 /// credited against the class. See issues #346, #387.
1643 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1644 pub is_instance_returning_static: bool,
1645 /// True when this is an instance class method whose call result is an
1646 /// instance of the same class. Qualifies when the declared return type
1647 /// matches the class name (`setX(): EventBuilder { ... }`) or when the
1648 /// body's last statement is `return this`. The analyze layer walks fluent
1649 /// chains (`Class.factory().setX().setY()`) only through methods carrying
1650 /// this flag, so the chain stops at a non-self-returning method like
1651 /// `.build()`. See issue #387.
1652 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1653 pub is_self_returning: bool,
1654}
1655
1656/// The kind of member.
1657#[derive(
1658 Debug,
1659 Clone,
1660 Copy,
1661 PartialEq,
1662 Eq,
1663 serde::Serialize,
1664 serde::Deserialize,
1665 bitcode::Encode,
1666 bitcode::Decode,
1667)]
1668#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1669#[serde(rename_all = "snake_case")]
1670pub enum MemberKind {
1671 /// A TypeScript enum member.
1672 EnumMember,
1673 /// A class method.
1674 ClassMethod,
1675 /// A class property.
1676 ClassProperty,
1677 /// A member exported from a TypeScript namespace.
1678 NamespaceMember,
1679 /// A member declared by a store object (Pinia `state` / `getters` /
1680 /// `actions` key, or a setup-store returned key). Cross-graph dead-member
1681 /// detection: a store member never accessed by any consumer project-wide.
1682 StoreMember,
1683}
1684
1685/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
1686#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
1687pub struct MemberAccess {
1688 /// The identifier being accessed (the import name).
1689 pub object: String,
1690 /// The member being accessed.
1691 pub member: String,
1692}
1693
1694/// Direct export declarations that TypeScript treats as one merged symbol.
1695///
1696/// Spans identify the exact declaration slots without conflating unrelated
1697/// type/value declarations that happen to share a name.
1698#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1699#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1700pub struct DeclarationMergeFact {
1701 /// Identifier spans for the declarations in this merge group.
1702 pub export_spans: Vec<(u32, u32)>,
1703}
1704
1705/// A default import binding consumed outside a statically known member access.
1706///
1707/// Resolution decides whether the target is an object-shaped module such as a
1708/// CSS Module or a proven static CommonJS object map. Keeping this fact
1709/// target-agnostic lets aliases and extensionless specifiers use the resolved
1710/// target path without broadening ordinary default-import behavior.
1711#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1712#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1713pub struct DefaultImportWholeObjectUseFact {
1714 /// Local binding name in the importing module.
1715 pub local_name: String,
1716}
1717
1718/// A typed extraction fact for cross-layer analysis.
1719#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1720#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1721#[serde(tag = "kind", rename_all = "snake_case")]
1722pub enum SemanticFact {
1723 /// A class member referenced from an Angular template, host binding, or
1724 /// component metadata entry.
1725 AngularTemplateMemberAccess(AngularTemplateMemberAccessFact),
1726 /// An Angular component field whose value is an array of a class.
1727 AngularComponentFieldArrayType(AngularComponentFieldArrayTypeFact),
1728 /// An Angular component spreads `this` into an object literal, so component
1729 /// input/output usage is opaque.
1730 AngularThisSpread(AngularThisSpreadFact),
1731 /// A member access on a value returned by an imported static factory call.
1732 FactoryCallMemberAccess(FactoryCallMemberAccessFact),
1733 /// A member access on a value returned by an imported free-function factory
1734 /// (`const x = importedFactory(); x.member`). See issue #1441 (Part A).
1735 FactoryFnMemberAccess(FactoryFnMemberAccessFact),
1736 /// A member access reached through a property of a value whose declared
1737 /// type is an imported named type (`this.opts.c.optM()` where `opts` is
1738 /// typed by an imported interface). See issue #1785.
1739 TypedPropertyMemberAccess(TypedPropertyMemberAccessFact),
1740 /// A member access on a fluent chain rooted at an imported static factory.
1741 FluentChainMemberAccess(FluentChainMemberAccessFact),
1742 /// A member access on a fluent chain rooted at a `new` expression.
1743 FluentChainNewMemberAccess(FluentChainNewMemberAccessFact),
1744 /// A member access on a Playwright fixture object inside a test callback.
1745 PlaywrightFixtureUse(PlaywrightFixtureUseFact),
1746 /// A Playwright fixture definition declared by a typed `test.extend<T>()`.
1747 PlaywrightFixtureDefinition(PlaywrightFixtureDefinitionFact),
1748 /// A Playwright fixture wrapper alias declared by `mergeTests` or `.extend`.
1749 PlaywrightFixtureAlias(PlaywrightFixtureAliasFact),
1750 /// A nested Playwright fixture binding declared by a fixture type alias.
1751 PlaywrightFixtureType(PlaywrightFixtureTypeFact),
1752 /// An exported value whose runtime instance targets a local class or interface.
1753 InstanceExportBinding(InstanceExportBindingFact),
1754 /// A dynamic custom-element tag render that makes static Lit tag credit opaque.
1755 DynamicCustomElementRender(DynamicCustomElementRenderFact),
1756 /// A factory-returned value consumed in a way that can expose ANY property
1757 /// (`const { a, ...rest } = importedFactory()`, a computed destructure key).
1758 /// The returned class must be treated as wholly used: crediting only the
1759 /// visible keys would leave a live member reported as dead.
1760 ///
1761 /// Appended, never inserted: `bitcode` encodes an enum by ordinal, so moving an
1762 /// existing variant would make an old cache decode one fact as another.
1763 FactoryFnWholeObject(FactoryFnWholeObjectFact),
1764 /// A member access reached through a property of a value returned by an
1765 /// imported factory that returns an object literal (`const ui = createUi();
1766 /// ui.orders.member`). Appended after `FactoryFnWholeObject`, never inserted
1767 /// (bitcode encodes by ordinal). See issue #1858.
1768 FactoryReturnObjectPropertyAccess(FactoryReturnObjectPropertyAccessFact),
1769 /// A `this.<field>.<member>` access tied to its exact enclosing class.
1770 /// Appended because bitcode encodes enum variants by ordinal.
1771 ClassThisMemberAccess(ClassThisMemberAccessFact),
1772 /// A whole-object use of `this.<field>...` tied to its exact enclosing class.
1773 /// Appended because bitcode encodes enum variants by ordinal.
1774 ClassThisWholeObjectUse(ClassThisWholeObjectUseFact),
1775 /// An ordered Vitest module-mock operation with direct imported-`vi`
1776 /// provenance.
1777 ///
1778 /// Appended because bitcode encodes enum variants by ordinal. The ordinary
1779 /// dynamic-import fact for the same source remains authoritative for graph
1780 /// reachability and unresolved-import diagnostics.
1781 VitestModuleMockOperation(VitestModuleMockOperationFact),
1782 /// Direct declarations that form one legal TypeScript declaration merge.
1783 /// Appended because bitcode encodes enum variants by ordinal.
1784 DeclarationMerge(DeclarationMergeFact),
1785 /// A named type whose direct receiver surface is contributed by another
1786 /// named type (for example `Pick<Base, ...>` or a union constituent).
1787 /// Appended because bitcode encodes enum variants by ordinal.
1788 TypeAliasSurfaceTarget(TypeAliasSurfaceTargetFact),
1789 /// A string-valued TypeScript enum member available as a static property key.
1790 /// Appended because bitcode encodes enum variants by ordinal.
1791 StringEnumMemberValue(StringEnumMemberValueFact),
1792 /// A computed property access keyed by a static enum member.
1793 /// Appended because bitcode encodes enum variants by ordinal.
1794 ComputedEnumKeyUse(ComputedEnumKeyUseFact),
1795 /// A directly declared non-optional member required by a named interface
1796 /// or object type.
1797 /// Appended because bitcode encodes enum variants by ordinal.
1798 RequiredTypeMember(RequiredTypeMemberFact),
1799 /// The file's complete CommonJS assignment surface is exactly one
1800 /// top-level `module.exports = { ... }` object literal whose keys are all
1801 /// static and which has no transpilation marker or competing assignment.
1802 /// Appended because bitcode encodes enum variants by ordinal.
1803 CjsSingleStaticObjectMap,
1804 /// A default import binding was handed on as a whole object.
1805 /// Appended because bitcode encodes enum variants by ordinal.
1806 DefaultImportWholeObjectUse(DefaultImportWholeObjectUseFact),
1807}
1808
1809/// Iterate Angular template member names from typed semantic facts.
1810fn angular_template_member_names_from_parts(
1811 semantic_facts: &[SemanticFact],
1812) -> impl Iterator<Item = &str> {
1813 semantic_facts.iter().filter_map(|fact| {
1814 if let SemanticFact::AngularTemplateMemberAccess(access) = fact {
1815 Some(access.member.as_str())
1816 } else {
1817 None
1818 }
1819 })
1820}
1821
1822/// Iterate Angular template member names from a module's typed facts.
1823pub fn angular_template_member_names(module: &ModuleInfo) -> impl Iterator<Item = &str> {
1824 angular_template_member_names_from_parts(&module.semantic_facts)
1825}
1826
1827/// Return true when the fact slice contains any Angular template member
1828/// reference.
1829#[must_use]
1830fn has_angular_template_members_from_parts(semantic_facts: &[SemanticFact]) -> bool {
1831 angular_template_member_names_from_parts(semantic_facts)
1832 .next()
1833 .is_some()
1834}
1835
1836/// Return true when the module contains any Angular template member reference.
1837#[must_use]
1838pub fn has_angular_template_members(module: &ModuleInfo) -> bool {
1839 has_angular_template_members_from_parts(&module.semantic_facts)
1840}
1841
1842/// Return true when a module spreads `this` in Angular template context.
1843#[must_use]
1844pub fn has_angular_this_spread(module: &ModuleInfo) -> bool {
1845 SemanticFactView::new(&module.semantic_facts, &module.member_accesses).has_angular_this_spread()
1846}
1847
1848/// Return true when a module contains a dynamic custom-element render.
1849#[must_use]
1850pub fn has_dynamic_custom_element_render(module: &ModuleInfo) -> bool {
1851 module
1852 .semantic_facts
1853 .iter()
1854 .any(|fact| matches!(fact, SemanticFact::DynamicCustomElementRender(_)))
1855}
1856
1857/// Typed-first view over semantic extraction facts.
1858///
1859/// Extraction populates `semantic_facts` directly. The `member_accesses` slice
1860/// remains available for consumers that need ordinary source member accesses,
1861/// but it is no longer decoded as a string protocol for semantic facts.
1862#[derive(Debug, Clone, Copy)]
1863pub struct SemanticFactView<'a> {
1864 semantic_facts: &'a [SemanticFact],
1865 member_accesses: &'a [MemberAccess],
1866}
1867
1868impl<'a> SemanticFactView<'a> {
1869 /// Create a typed semantic fact view from current semantic facts plus
1870 /// ordinary source member accesses.
1871 #[must_use]
1872 pub const fn new(
1873 semantic_facts: &'a [SemanticFact],
1874 member_accesses: &'a [MemberAccess],
1875 ) -> Self {
1876 Self {
1877 semantic_facts,
1878 member_accesses,
1879 }
1880 }
1881
1882 /// Iterate typed semantic facts.
1883 pub fn facts(self) -> impl Iterator<Item = &'a SemanticFact> + 'a {
1884 self.semantic_facts.iter()
1885 }
1886
1887 /// Iterate Angular template member references.
1888 pub fn angular_template_member_names(self) -> impl Iterator<Item = &'a str> + 'a {
1889 angular_template_member_names_from_parts(self.semantic_facts)
1890 }
1891
1892 /// Collect Angular component field array-type facts.
1893 pub fn angular_component_field_array_types(self) -> Vec<AngularComponentFieldArrayTypeFact> {
1894 angular_component_field_array_type_facts(self.semantic_facts)
1895 .cloned()
1896 .collect()
1897 }
1898
1899 /// Return true when any Angular template member reference exists.
1900 #[must_use]
1901 pub fn has_angular_template_members(self) -> bool {
1902 self.angular_template_member_names().next().is_some()
1903 }
1904
1905 /// Return true when a module spreads `this` in Angular template context.
1906 #[must_use]
1907 pub fn has_angular_this_spread(self) -> bool {
1908 self.semantic_facts
1909 .iter()
1910 .any(|fact| matches!(fact, SemanticFact::AngularThisSpread(_)))
1911 }
1912
1913 /// Iterate ordinary source member accesses.
1914 pub fn ordinary_member_accesses(self) -> impl Iterator<Item = &'a MemberAccess> + 'a {
1915 self.member_accesses.iter()
1916 }
1917
1918 /// Collect class-scoped `this` member-access facts.
1919 pub fn class_this_member_accesses(self) -> Vec<ClassThisMemberAccessFact> {
1920 class_this_member_access_facts(self.semantic_facts)
1921 .cloned()
1922 .collect()
1923 }
1924
1925 /// Collect class-scoped `this` whole-object-use facts.
1926 pub fn class_this_whole_object_uses(self) -> Vec<ClassThisWholeObjectUseFact> {
1927 class_this_whole_object_use_facts(self.semantic_facts)
1928 .cloned()
1929 .collect()
1930 }
1931
1932 /// Collect instance-export binding facts.
1933 pub fn instance_export_bindings(self) -> Vec<InstanceExportBindingFact> {
1934 instance_export_binding_facts(self.semantic_facts)
1935 .cloned()
1936 .collect()
1937 }
1938
1939 /// Collect static factory call member facts.
1940 pub fn factory_call_member_accesses(self) -> Vec<FactoryCallMemberAccessFact> {
1941 factory_call_member_access_facts(self.semantic_facts)
1942 .cloned()
1943 .collect()
1944 }
1945
1946 /// Collect free-function factory-return member facts.
1947 pub fn factory_fn_member_accesses(self) -> Vec<FactoryFnMemberAccessFact> {
1948 factory_fn_member_access_facts(self.semantic_facts)
1949 .cloned()
1950 .collect()
1951 }
1952
1953 /// Collect factory-return whole-object consumption facts.
1954 pub fn factory_fn_whole_objects(self) -> Vec<FactoryFnWholeObjectFact> {
1955 factory_fn_whole_object_facts(self.semantic_facts)
1956 .cloned()
1957 .collect()
1958 }
1959
1960 /// Collect object-literal factory-return property member facts.
1961 pub fn factory_return_object_property_accesses(
1962 self,
1963 ) -> Vec<FactoryReturnObjectPropertyAccessFact> {
1964 factory_return_object_property_access_facts(self.semantic_facts)
1965 .cloned()
1966 .collect()
1967 }
1968
1969 /// Collect typed-property-hop member facts.
1970 pub fn typed_property_member_accesses(self) -> Vec<TypedPropertyMemberAccessFact> {
1971 typed_property_member_access_facts(self.semantic_facts)
1972 .cloned()
1973 .collect()
1974 }
1975
1976 /// Collect members whose presence is required by a named structural type.
1977 pub fn required_type_members(self) -> impl Iterator<Item = &'a RequiredTypeMemberFact> + 'a {
1978 required_type_member_facts(self.semantic_facts)
1979 }
1980
1981 /// Collect type-alias receiver-surface edges.
1982 pub fn type_alias_surface_targets(self) -> Vec<TypeAliasSurfaceTargetFact> {
1983 type_alias_surface_target_facts(self.semantic_facts)
1984 .cloned()
1985 .collect()
1986 }
1987
1988 /// Collect string-valued enum member definitions.
1989 pub fn string_enum_member_values(self) -> Vec<StringEnumMemberValueFact> {
1990 string_enum_member_value_facts(self.semantic_facts)
1991 .cloned()
1992 .collect()
1993 }
1994
1995 /// Collect computed property accesses keyed by enum members.
1996 pub fn computed_enum_key_uses(self) -> Vec<ComputedEnumKeyUseFact> {
1997 computed_enum_key_use_facts(self.semantic_facts)
1998 .cloned()
1999 .collect()
2000 }
2001
2002 /// Collect static factory fluent-chain member facts.
2003 pub fn fluent_chain_member_accesses(self) -> Vec<FluentChainMemberAccessFact> {
2004 fluent_chain_member_access_facts(self.semantic_facts)
2005 .cloned()
2006 .collect()
2007 }
2008
2009 /// Collect constructor-rooted fluent-chain member facts.
2010 pub fn fluent_chain_new_member_accesses(self) -> Vec<FluentChainNewMemberAccessFact> {
2011 fluent_chain_new_member_access_facts(self.semantic_facts)
2012 .cloned()
2013 .collect()
2014 }
2015
2016 /// Collect Playwright fixture-use facts.
2017 pub fn playwright_fixture_uses(self) -> Vec<PlaywrightFixtureUseFact> {
2018 playwright_fixture_use_facts(self.semantic_facts)
2019 .cloned()
2020 .collect()
2021 }
2022
2023 /// Collect Playwright fixture-definition facts.
2024 pub fn playwright_fixture_definitions(self) -> Vec<PlaywrightFixtureDefinitionFact> {
2025 playwright_fixture_definition_facts(self.semantic_facts)
2026 .cloned()
2027 .collect()
2028 }
2029
2030 /// Collect Playwright fixture-alias facts.
2031 pub fn playwright_fixture_aliases(self) -> Vec<PlaywrightFixtureAliasFact> {
2032 playwright_fixture_alias_facts(self.semantic_facts)
2033 .cloned()
2034 .collect()
2035 }
2036
2037 /// Collect Playwright fixture-type facts.
2038 pub fn playwright_fixture_types(self) -> Vec<PlaywrightFixtureTypeFact> {
2039 playwright_fixture_type_facts(self.semantic_facts)
2040 .cloned()
2041 .collect()
2042 }
2043}
2044
2045/// Iterate ordinary whole-object uses.
2046pub fn ordinary_whole_object_uses(whole_object_uses: &[String]) -> impl Iterator<Item = &str> {
2047 whole_object_uses.iter().map(String::as_str)
2048}
2049
2050/// Iterate typed instance-export binding facts.
2051fn instance_export_binding_facts(
2052 semantic_facts: &[SemanticFact],
2053) -> impl Iterator<Item = &InstanceExportBindingFact> {
2054 semantic_facts.iter().filter_map(|fact| {
2055 if let SemanticFact::InstanceExportBinding(access) = fact {
2056 Some(access)
2057 } else {
2058 None
2059 }
2060 })
2061}
2062
2063fn class_this_member_access_facts(
2064 semantic_facts: &[SemanticFact],
2065) -> impl Iterator<Item = &ClassThisMemberAccessFact> {
2066 semantic_facts.iter().filter_map(|fact| {
2067 if let SemanticFact::ClassThisMemberAccess(access) = fact {
2068 Some(access)
2069 } else {
2070 None
2071 }
2072 })
2073}
2074
2075fn class_this_whole_object_use_facts(
2076 semantic_facts: &[SemanticFact],
2077) -> impl Iterator<Item = &ClassThisWholeObjectUseFact> {
2078 semantic_facts.iter().filter_map(|fact| {
2079 if let SemanticFact::ClassThisWholeObjectUse(access) = fact {
2080 Some(access)
2081 } else {
2082 None
2083 }
2084 })
2085}
2086
2087fn angular_component_field_array_type_facts(
2088 semantic_facts: &[SemanticFact],
2089) -> impl Iterator<Item = &AngularComponentFieldArrayTypeFact> {
2090 semantic_facts.iter().filter_map(|fact| {
2091 if let SemanticFact::AngularComponentFieldArrayType(access) = fact {
2092 Some(access)
2093 } else {
2094 None
2095 }
2096 })
2097}
2098
2099/// Iterate typed factory-call member facts.
2100fn factory_call_member_access_facts(
2101 semantic_facts: &[SemanticFact],
2102) -> impl Iterator<Item = &FactoryCallMemberAccessFact> {
2103 semantic_facts.iter().filter_map(|fact| {
2104 if let SemanticFact::FactoryCallMemberAccess(access) = fact {
2105 Some(access)
2106 } else {
2107 None
2108 }
2109 })
2110}
2111
2112/// Iterate typed free-function factory-return member facts.
2113fn factory_fn_member_access_facts(
2114 semantic_facts: &[SemanticFact],
2115) -> impl Iterator<Item = &FactoryFnMemberAccessFact> {
2116 semantic_facts.iter().filter_map(|fact| {
2117 if let SemanticFact::FactoryFnMemberAccess(access) = fact {
2118 Some(access)
2119 } else {
2120 None
2121 }
2122 })
2123}
2124
2125fn factory_fn_whole_object_facts(
2126 semantic_facts: &[SemanticFact],
2127) -> impl Iterator<Item = &FactoryFnWholeObjectFact> {
2128 semantic_facts.iter().filter_map(|fact| {
2129 if let SemanticFact::FactoryFnWholeObject(fact) = fact {
2130 Some(fact)
2131 } else {
2132 None
2133 }
2134 })
2135}
2136
2137/// Iterate object-literal factory-return property member facts.
2138fn factory_return_object_property_access_facts(
2139 semantic_facts: &[SemanticFact],
2140) -> impl Iterator<Item = &FactoryReturnObjectPropertyAccessFact> {
2141 semantic_facts.iter().filter_map(|fact| {
2142 if let SemanticFact::FactoryReturnObjectPropertyAccess(access) = fact {
2143 Some(access)
2144 } else {
2145 None
2146 }
2147 })
2148}
2149
2150/// Iterate typed fluent-chain member facts.
2151fn fluent_chain_member_access_facts(
2152 semantic_facts: &[SemanticFact],
2153) -> impl Iterator<Item = &FluentChainMemberAccessFact> {
2154 semantic_facts.iter().filter_map(|fact| {
2155 if let SemanticFact::FluentChainMemberAccess(access) = fact {
2156 Some(access)
2157 } else {
2158 None
2159 }
2160 })
2161}
2162
2163/// Iterate typed-property-hop member facts.
2164fn typed_property_member_access_facts(
2165 semantic_facts: &[SemanticFact],
2166) -> impl Iterator<Item = &TypedPropertyMemberAccessFact> {
2167 semantic_facts.iter().filter_map(|fact| {
2168 if let SemanticFact::TypedPropertyMemberAccess(access) = fact {
2169 Some(access)
2170 } else {
2171 None
2172 }
2173 })
2174}
2175
2176fn required_type_member_facts(
2177 semantic_facts: &[SemanticFact],
2178) -> impl Iterator<Item = &RequiredTypeMemberFact> {
2179 semantic_facts.iter().filter_map(|fact| {
2180 if let SemanticFact::RequiredTypeMember(required) = fact {
2181 Some(required)
2182 } else {
2183 None
2184 }
2185 })
2186}
2187
2188fn type_alias_surface_target_facts(
2189 semantic_facts: &[SemanticFact],
2190) -> impl Iterator<Item = &TypeAliasSurfaceTargetFact> {
2191 semantic_facts.iter().filter_map(|fact| {
2192 if let SemanticFact::TypeAliasSurfaceTarget(fact) = fact {
2193 Some(fact)
2194 } else {
2195 None
2196 }
2197 })
2198}
2199
2200fn string_enum_member_value_facts(
2201 semantic_facts: &[SemanticFact],
2202) -> impl Iterator<Item = &StringEnumMemberValueFact> {
2203 semantic_facts.iter().filter_map(|fact| {
2204 if let SemanticFact::StringEnumMemberValue(fact) = fact {
2205 Some(fact)
2206 } else {
2207 None
2208 }
2209 })
2210}
2211
2212fn computed_enum_key_use_facts(
2213 semantic_facts: &[SemanticFact],
2214) -> impl Iterator<Item = &ComputedEnumKeyUseFact> {
2215 semantic_facts.iter().filter_map(|fact| {
2216 if let SemanticFact::ComputedEnumKeyUse(fact) = fact {
2217 Some(fact)
2218 } else {
2219 None
2220 }
2221 })
2222}
2223
2224/// Iterate typed constructor-rooted fluent-chain member facts.
2225fn fluent_chain_new_member_access_facts(
2226 semantic_facts: &[SemanticFact],
2227) -> impl Iterator<Item = &FluentChainNewMemberAccessFact> {
2228 semantic_facts.iter().filter_map(|fact| {
2229 if let SemanticFact::FluentChainNewMemberAccess(access) = fact {
2230 Some(access)
2231 } else {
2232 None
2233 }
2234 })
2235}
2236
2237/// Iterate typed Playwright fixture-use facts.
2238fn playwright_fixture_use_facts(
2239 semantic_facts: &[SemanticFact],
2240) -> impl Iterator<Item = &PlaywrightFixtureUseFact> {
2241 semantic_facts.iter().filter_map(|fact| {
2242 if let SemanticFact::PlaywrightFixtureUse(access) = fact {
2243 Some(access)
2244 } else {
2245 None
2246 }
2247 })
2248}
2249
2250/// Iterate typed Playwright fixture-definition facts.
2251fn playwright_fixture_definition_facts(
2252 semantic_facts: &[SemanticFact],
2253) -> impl Iterator<Item = &PlaywrightFixtureDefinitionFact> {
2254 semantic_facts.iter().filter_map(|fact| {
2255 if let SemanticFact::PlaywrightFixtureDefinition(access) = fact {
2256 Some(access)
2257 } else {
2258 None
2259 }
2260 })
2261}
2262
2263/// Iterate typed Playwright fixture-alias facts.
2264fn playwright_fixture_alias_facts(
2265 semantic_facts: &[SemanticFact],
2266) -> impl Iterator<Item = &PlaywrightFixtureAliasFact> {
2267 semantic_facts.iter().filter_map(|fact| {
2268 if let SemanticFact::PlaywrightFixtureAlias(access) = fact {
2269 Some(access)
2270 } else {
2271 None
2272 }
2273 })
2274}
2275
2276/// Iterate typed Playwright fixture-type facts.
2277fn playwright_fixture_type_facts(
2278 semantic_facts: &[SemanticFact],
2279) -> impl Iterator<Item = &PlaywrightFixtureTypeFact> {
2280 semantic_facts.iter().filter_map(|fact| {
2281 if let SemanticFact::PlaywrightFixtureType(access) = fact {
2282 Some(access)
2283 } else {
2284 None
2285 }
2286 })
2287}
2288
2289/// A member name referenced from an Angular template surface.
2290#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2291#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2292pub struct AngularTemplateMemberAccessFact {
2293 /// Referenced class member name.
2294 pub member: String,
2295}
2296
2297/// A typed Angular component field that exposes array elements to templates.
2298#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2299#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2300pub struct AngularComponentFieldArrayTypeFact {
2301 /// Component field name used as the template iterable.
2302 pub field: String,
2303 /// Array element class name.
2304 pub element_class: String,
2305}
2306
2307/// Opaque Angular `{ ...this }` forwarding marker.
2308#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2309#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2310pub struct AngularThisSpreadFact;
2311
2312/// A member access on a static factory call result.
2313#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2314#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2315pub struct FactoryCallMemberAccessFact {
2316 /// Local imported class or namespace object used as the factory callee.
2317 pub callee_object: String,
2318 /// Static factory method invoked on the callee object.
2319 pub callee_method: String,
2320 /// Member accessed on the returned instance-like object.
2321 pub member: String,
2322}
2323
2324/// A member access on a value returned by an imported free-function factory.
2325///
2326/// `const x = importedFactory(); x.member` emits one fact per first-level read
2327/// on `x`. The analyze layer resolves `callee_name` through the consumer's
2328/// imports to the factory's origin module, reads that module's
2329/// `exported_factory_returns` to learn the returned class's local name, resolves
2330/// THAT through the factory module's own imports to the class export, and
2331/// credits `member` on the class. See issue #1441 (Part A).
2332#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2333#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2334pub struct FactoryFnMemberAccessFact {
2335 /// Local imported function used as the factory callee.
2336 pub callee_name: String,
2337 /// Member accessed on the returned instance-like object.
2338 pub member: String,
2339}
2340
2341/// A factory-returned value consumed opaquely, so every member of the class it
2342/// returns must be treated as used.
2343#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2344#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2345pub struct FactoryFnWholeObjectFact {
2346 /// Local imported function used as the factory callee.
2347 pub callee_name: String,
2348}
2349
2350/// A member access reached through a property of a value returned by an imported
2351/// factory that returns an object literal.
2352///
2353/// `const ui = createUi(); ui.orders.member` emits one fact per member read on a
2354/// factory-result property. The analyze layer resolves `callee_name` through the
2355/// consumer's imports to the factory's origin module, reads that module's
2356/// `exported_factory_return_object_shapes` to find the property whose path equals
2357/// `property_path` and its class local name, resolves THAT through the factory
2358/// module's own imports to the class export, and credits `member` on the class
2359/// (gated on the export actually being a class with members). See issue #1858.
2360#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2361#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2362pub struct FactoryReturnObjectPropertyAccessFact {
2363 /// Local imported function used as the factory callee.
2364 pub callee_name: String,
2365 /// Dotted property path between the factory-result local and the final member
2366 /// (e.g. `"orders"` for `ui.orders.member`, `"invoke.orders"` for `ui.invoke.orders.member`).
2367 pub property_path: String,
2368 /// Member accessed on the terminal property's instance.
2369 pub member: String,
2370}
2371
2372/// A member access reached through a typed property hop that the extraction
2373/// layer could not resolve locally.
2374///
2375/// `constructor(private opts: Opts) { ... this.opts.c.optM() }` where `Opts`
2376/// is NOT declared in this file emits
2377/// `TypedPropertyMemberAccessFact { type_name: "Opts", property_path: "c", member: "optM" }`.
2378/// The analyze layer resolves `type_name` through the consumer's imports to the
2379/// declaring module, walks `property_path` through that module's
2380/// `type_member_types`, resolves the terminal type name through the declaring
2381/// module's own imports, and credits `member` on the resolved class (gated on
2382/// the export actually being a class with members). See issue #1785.
2383#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2384#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2385pub struct TypedPropertyMemberAccessFact {
2386 /// Local (usually imported) named-type symbol the receiver is typed by.
2387 pub type_name: String,
2388 /// Remaining dotted property segments between the typed binding and the
2389 /// final member (e.g. `"c"` for `this.opts.c.optM()`).
2390 pub property_path: String,
2391 /// Member accessed on the terminal property's instance.
2392 pub member: String,
2393}
2394
2395/// A class member directly required by a named structural type.
2396///
2397/// Optional properties and methods are excluded: removing an optional
2398/// implementation can preserve assignability, while removing a required one
2399/// from an explicit `implements` contract cannot.
2400#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2401#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2402pub struct RequiredTypeMemberFact {
2403 /// Module-local interface or object-type alias name.
2404 pub type_name: String,
2405 /// Static required property or method name.
2406 pub member: String,
2407}
2408
2409/// One direct contributor to a named type alias's receiver surface.
2410///
2411/// Nested property types are deliberately excluded: in
2412/// `{ nested: Nested }`, `Alias.member` does not access `Nested.member`.
2413#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2414#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2415pub struct TypeAliasSurfaceTargetFact {
2416 /// Module-local alias declaration name.
2417 pub alias_name: String,
2418 /// Module-local or imported named type contributing the direct surface.
2419 pub target_name: String,
2420}
2421
2422/// A statically known string value of a TypeScript enum member.
2423#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2424#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2425pub struct StringEnumMemberValueFact {
2426 /// Module-local enum declaration name.
2427 pub enum_name: String,
2428 /// Static enum member name.
2429 pub member_name: String,
2430 /// Exact string initializer value.
2431 pub value: String,
2432}
2433
2434/// A computed property access whose key is a static enum member.
2435#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2436#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2437pub struct ComputedEnumKeyUseFact {
2438 /// Local enum object used as the key source.
2439 pub key_object: String,
2440 /// Static member selected from the enum object.
2441 pub key_member: String,
2442}
2443
2444/// A member access on a fluent chain rooted at a static factory call.
2445#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2446#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2447pub struct FluentChainMemberAccessFact {
2448 /// Local imported class or namespace object used as the chain root.
2449 pub root_object: String,
2450 /// Static factory method that starts the fluent chain.
2451 pub root_method: String,
2452 /// Intermediate fluent methods between the root method and final member.
2453 pub chain: Vec<String>,
2454 /// Member accessed at this chain step.
2455 pub member: String,
2456}
2457
2458/// A member access on a fluent chain rooted at a `new` expression.
2459#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2460#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2461pub struct FluentChainNewMemberAccessFact {
2462 /// Local imported class constructed by the `new` expression.
2463 pub class_name: String,
2464 /// Intermediate fluent methods between construction and final member.
2465 pub chain: Vec<String>,
2466 /// Member accessed at this chain step.
2467 pub member: String,
2468}
2469
2470/// A member access on a Playwright fixture object inside a test callback.
2471#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2472#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2473pub struct PlaywrightFixtureUseFact {
2474 /// Local test function or wrapper used as the callback callee.
2475 pub test_name: String,
2476 /// Fixture name or dotted fixture path referenced in the callback.
2477 pub fixture_name: String,
2478 /// Member accessed on the fixture target.
2479 pub member: String,
2480}
2481
2482/// A Playwright fixture definition declared by a typed `test.extend<T>()`.
2483#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2484#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2485pub struct PlaywrightFixtureDefinitionFact {
2486 /// Local test function or wrapper receiving the fixture definition.
2487 pub test_name: String,
2488 /// Fixture name or dotted fixture path declared by the fixture type.
2489 pub fixture_name: String,
2490 /// Local type symbol used as the fixture target.
2491 pub type_name: String,
2492}
2493
2494/// A Playwright fixture wrapper alias declared by `mergeTests` or `.extend`.
2495#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2496#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2497pub struct PlaywrightFixtureAliasFact {
2498 /// Local test function or wrapper that inherits fixture definitions.
2499 pub test_name: String,
2500 /// Local test function or wrapper inherited by `test_name`.
2501 pub base_name: String,
2502}
2503
2504/// A nested Playwright fixture binding declared by a fixture type alias.
2505#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2506#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2507pub struct PlaywrightFixtureTypeFact {
2508 /// Local type alias containing the nested fixture binding.
2509 pub alias_name: String,
2510 /// Fixture name or dotted fixture path declared inside the type alias.
2511 pub fixture_name: String,
2512 /// Local type symbol used as the nested fixture target.
2513 pub type_name: String,
2514}
2515
2516/// An exported value whose runtime instance targets a local class or interface.
2517#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2518#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2519pub struct InstanceExportBindingFact {
2520 /// Exported binding name.
2521 pub export_name: String,
2522 /// Local class or interface symbol used as the instance target.
2523 pub target_name: String,
2524}
2525
2526/// Opaque marker for a dynamic custom-element render site.
2527#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2528#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2529pub struct DynamicCustomElementRenderFact;
2530
2531/// The action performed by a Vitest module-mock operation.
2532#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2533#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2534#[serde(rename_all = "snake_case")]
2535pub enum VitestModuleMockAction {
2536 /// Register a mock. `factory_replaces_original` is true only when the
2537 /// factory is structurally closed and cannot load the original module.
2538 ///
2539 /// Automock (`vi.mock` / `jest.mock` without a factory) is always
2540 /// `factory_replaces_original: false` by decision (issue #2082). For
2541 /// Vitest, the runner derives the mocked shape by importing the original
2542 /// module, so its top-level code executes at collection time, and
2543 /// file-level masking cannot express "module evaluated but exports
2544 /// stubbed". For Jest, a `__mocks__` sibling takes precedence and the
2545 /// original is genuinely not required, but the manual mock itself may
2546 /// load the original (`jest.requireActual`), and proving it never does
2547 /// would need a cross-file factory proof. Both runners therefore keep
2548 /// coverage credit for the automock form.
2549 Mock {
2550 /// Whether the factory provably replaces the original module.
2551 factory_replaces_original: bool,
2552 },
2553 /// Remove a registered mock and restore the original module.
2554 Unmock,
2555}
2556
2557impl VitestModuleMockAction {
2558 /// Whether this operation registers a proven complete replacement.
2559 #[must_use]
2560 pub const fn replaces_original(self) -> bool {
2561 matches!(
2562 self,
2563 Self::Mock {
2564 factory_replaces_original: true
2565 }
2566 )
2567 }
2568}
2569
2570/// Ordered Vitest module-mock operation with a static source target.
2571///
2572/// The declaring [`ModuleInfo::file_id`] owns the test-root provenance. The
2573/// resolver consumes `source` through its canonical specifier pipeline; this
2574/// fact deliberately carries no resolved path or duplicate diagnostic span.
2575#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2576#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2577pub struct VitestModuleMockOperationFact {
2578 /// Static module specifier passed to `vi.mock` or `vi.unmock`.
2579 pub source: String,
2580 /// Source-order position of the call within the declaring module.
2581 pub call_start: u32,
2582 /// Typed mock or unmock action.
2583 pub action: VitestModuleMockAction,
2584}
2585
2586/// A `this`-rooted member access with exact enclosing-class provenance.
2587#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2588#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2589pub struct ClassThisMemberAccessFact {
2590 /// Enclosing class local name, or `default` for an anonymous default class.
2591 pub class_local_name: String,
2592 /// Dotted receiver spelling beginning with `this.`.
2593 pub object: String,
2594 /// Terminal member being accessed.
2595 pub member: String,
2596}
2597
2598/// A whole-object use of a `this`-rooted chain with enclosing-class provenance.
2599#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2600#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2601pub struct ClassThisWholeObjectUseFact {
2602 /// Enclosing class local name, or `default` for an anonymous default class.
2603 pub class_local_name: String,
2604 /// Dotted receiver spelling beginning with `this.`.
2605 pub object: String,
2606}
2607
2608/// A statically flattenable callee path invoked in a module (e.g. `execSync`,
2609/// `child_process.exec`, `console.log`). One entry per unique `callee_path`
2610/// per module; the span anchors the first occurrence. Consumed by the
2611/// `boundaries.calls.forbidden` detector.
2612#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2613pub struct CalleeUse {
2614 /// The dotted or bare callee path as written at the call site.
2615 pub callee_path: String,
2616 /// Start byte offset of the first call site using this path.
2617 pub span_start: u32,
2618}
2619
2620/// A `"use client"` / `"use server"` directive string written as an expression
2621/// statement in `program.body` (NOT the leading prologue), so the RSC bundler
2622/// silently ignores it. One entry per offending occurrence. Consumed by the
2623/// `misplaced-directive` detector.
2624#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2625pub struct MisplacedDirectiveSite {
2626 /// `true` for `"use server"`, `false` for `"use client"`.
2627 pub is_server: bool,
2628 /// Start byte offset of the misplaced directive statement.
2629 pub span_start: u32,
2630}
2631
2632/// Which side of a dependency-injection link a call site represents.
2633#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2634pub enum DiRole {
2635 /// `provide(KEY, value)` / `app.provide(KEY, value)` / `setContext(KEY, value)`.
2636 Provide,
2637 /// `inject(KEY)` / `getContext(KEY)`.
2638 Inject,
2639}
2640
2641/// Which framework's DI API a call site came from (drives the finding message).
2642#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2643pub enum DiFramework {
2644 /// Vue `provide` / `inject` (from `vue` / `@vue/runtime-core`).
2645 Vue,
2646 /// Svelte `setContext` / `getContext` (from `svelte`).
2647 Svelte,
2648 /// Angular `inject(TOKEN)` / `@Inject(TOKEN)` (from `@angular/core`),
2649 /// matched against `{ provide: TOKEN, ... }` provider objects.
2650 Angular,
2651}
2652
2653/// A Vue `provide`/`inject` or Svelte `setContext`/`getContext` call site keyed
2654/// by an identifier symbol. The `key_local` is resolved at analyze time through
2655/// the consuming module's import/export tables to a canonical defining-site
2656/// export key, so a provide and an inject of the same shared symbol unify even
2657/// across barrel re-exports. Consumed by the `unprovided-inject` detector.
2658#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2659pub struct DiKeySite {
2660 /// The key identifier as written at the call site.
2661 pub key_local: String,
2662 /// Whether this is a provide or an inject.
2663 pub role: DiRole,
2664 /// Which framework's API this came from.
2665 pub framework: DiFramework,
2666 /// Start byte offset of the call expression (anchors the finding).
2667 pub span_start: u32,
2668}
2669
2670/// A component prop declared by Vue `<script setup>` `defineProps` or Svelte 5
2671/// `$props()`. `used_in_script` / `used_in_template` are set during extraction;
2672/// the `unused-component-prop` detector flags a prop where neither is true. See
2673/// `harvest_define_props` and `harvest_svelte_props` in `sfc_props.rs`.
2674#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2675pub struct ComponentProp {
2676 /// The declared prop name.
2677 pub name: String,
2678 /// The template/script-visible local binding name: the destructure alias for
2679 /// `const { name: alias } = defineProps()` or
2680 /// `let { name: alias } = $props()`, otherwise the prop name itself. A
2681 /// renamed prop is read through this local, so usage must be checked against
2682 /// it, not the declared name.
2683 pub local: String,
2684 /// Start byte offset of the prop declaration (anchors the finding).
2685 pub span_start: u32,
2686 /// Whether this prop is referenced in the component's `<script>` (a
2687 /// destructured local binding with a resolved reference, or a `props.<name>`
2688 /// member access). For React, this is set-in-body: a resolved reference to the
2689 /// destructured local anywhere in the component function body.
2690 pub used_in_script: bool,
2691 /// Whether this prop name is referenced in the component's `<template>`.
2692 /// Set by `apply_template_usage` when the template scanner credits the name.
2693 /// Always false for React (no template; React uses `used_in_script`).
2694 pub used_in_template: bool,
2695 /// The enclosing component name. Empty for Vue SFCs (one component per file,
2696 /// the file stem is the component, set by the detector). For React this is the
2697 /// component function/arrow name a prop was declared on, so the detector can
2698 /// emit the right `component_name` and apply the per-component abstain ladder
2699 /// (a file can declare several React components).
2700 pub component: String,
2701 /// React-only: `true` when the destructured prop local is referenced at least
2702 /// once OUTSIDE a child-JSX attribute value expression (a substantive
2703 /// consumption: a hook arg, a host-element child, a non-JSX-attr read). When
2704 /// `used_in_script` is true but this is false, the prop is referenced ONLY as
2705 /// the root of forwarded child attribute values, i.e. a pure pass-through.
2706 /// Always `false` for Vue (no forward-vs-consume distinction is computed).
2707 pub used_outside_forward: bool,
2708}
2709
2710/// A Vue `<script setup>` `defineEmits` declared event, harvested from the type
2711/// tuple-call form (`defineEmits<{ (e: 'foo'): void }>()`), the type object form
2712/// (`defineEmits<{ foo: [x: string] }>()`), or the runtime array form
2713/// (`defineEmits(['foo'])`). `used` is set during extraction when the bound emit
2714/// name is called as `emit('<name>')`. The `unused-component-emit` detector flags
2715/// an event where `used` is false. See `harvest_define_emits` in `sfc_props.rs`.
2716#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2717pub struct ComponentEmit {
2718 /// The declared emit event name.
2719 pub name: String,
2720 /// Start byte offset of the emit declaration (anchors the finding).
2721 pub span_start: u32,
2722 /// Whether this event is emitted via `emit('<name>')` somewhere in the
2723 /// component's `<script>`.
2724 pub used: bool,
2725}
2726
2727/// A Svelte custom event dispatched via `dispatch('<name>')`, where `dispatch`
2728/// is the binding from a `const dispatch = createEventDispatcher()` call. Only
2729/// literal-first-arg dispatches are recorded; a `dispatch(<nonLiteral>)` sets
2730/// `ModuleInfo::has_dynamic_dispatch` instead. Consumed by the
2731/// `unused-svelte-event` detector, which flags an event dispatched here but
2732/// listened to nowhere project-wide (the cross-file dead-output direction). The
2733/// span is a byte offset (not an `oxc_span::Span`) so the type round-trips
2734/// through the bitcode cache directly, mirroring `ComponentEmit::span_start`.
2735#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2736pub struct DispatchedEvent {
2737 /// The dispatched event name (the literal first argument).
2738 pub name: String,
2739 /// Start byte offset of the `dispatch(...)` call (anchors the finding).
2740 pub span_start: u32,
2741}
2742
2743/// A declared Angular component/directive input, harvested from an `@Input()`
2744/// decorator or a signal `input()` / `input.required()` / `model()` initializer
2745/// on an Angular-decorated class. Consumed by the `unused-component-input`
2746/// detector, which flags an input read nowhere in its own component (neither the
2747/// template nor the class body). The span is stored as a byte offset (not an
2748/// `oxc_span::Span`) so the type is cheap to mirror onto the cache, matching
2749/// `ComponentEmit::span_start`. `ModuleInfo` is not serialized, so no serde
2750/// attrs are derived here. `bitcode` derives let the type be mirrored directly
2751/// onto `CachedModule` (the same pattern as `ComponentEmit`).
2752#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2753pub struct AngularInputMember {
2754 /// The declared input name (the property key).
2755 pub name: String,
2756 /// Start byte offset of the property key (anchors the finding).
2757 pub span_start: u32,
2758}
2759
2760/// A declared Angular component/directive output, harvested from an `@Output()`
2761/// decorator or a signal `output()` / `outputFromObservable()` initializer on an
2762/// Angular-decorated class. Consumed by the `unused-component-output` detector,
2763/// which flags an output emitted nowhere in its own component. A `model()` is an
2764/// input and a framework-driven output, so it is recorded ONLY as an input and
2765/// never appears here (the implicit `update:` emit is framework-managed). The
2766/// span is a byte offset for the same reason as `AngularInputMember`.
2767#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2768pub struct AngularOutputMember {
2769 /// The declared output name (the property key).
2770 pub name: String,
2771 /// Start byte offset of the property key (anchors the finding).
2772 pub span_start: u32,
2773}
2774
2775/// A declared Angular `@Component` and its `selector` value(s), harvested from a
2776/// `@Component({ selector: '...' })` decorator. Consumed by the Angular arm of
2777/// the `unrendered-component` detector, which flags a component whose every
2778/// element selector is used in NO template project-wide (and that is not
2779/// referenced by class name anywhere, e.g. routed / bootstrapped / dynamically
2780/// rendered). A multi-selector string (`'app-foo, [appBar]'`) is split into the
2781/// `selectors` list. The span is stored as a byte offset (not an
2782/// `oxc_span::Span`) so the type round-trips through the bitcode cache directly,
2783/// mirroring `AngularInputMember::span_start`. `@Directive` is intentionally NOT
2784/// harvested here (directives have no template render). `ModuleInfo` is not
2785/// serialized, so no serde attrs are derived.
2786#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2787pub struct AngularComponentSelector {
2788 /// The declared selector strings for this component, split on `,`. A purely
2789 /// element-selector component has only `app-foo`-shaped entries; attribute
2790 /// (`[appFoo]`) and class (`.foo`) selectors are retained verbatim so the
2791 /// detector can abstain when ANY non-element selector is present.
2792 pub selectors: Vec<String>,
2793 /// Start byte offset of the component class declaration (anchors the
2794 /// finding).
2795 pub span_start: u32,
2796 /// The component class name (used to credit routed / bootstrapped / dynamic
2797 /// class-name references project-wide).
2798 pub class_name: String,
2799}
2800
2801/// A Lit / web-component custom element registered in a module via
2802/// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed by
2803/// the Lit arm of the `unrendered-component` detector. The span is stored as a
2804/// byte offset (not an `oxc_span::Span`) so the type round-trips through the
2805/// bitcode cache directly, mirroring `AngularComponentSelector::span_start`.
2806#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2807pub struct RegisteredCustomElement {
2808 /// The registered custom-element tag name (`x-foo`).
2809 pub tag: String,
2810 /// The registering class's local name, used for the public-API / export
2811 /// abstain (an exported / published element is rendered by a downstream
2812 /// consumer the scan cannot see). Empty for an anonymous
2813 /// `export default @customElement('x-foo') class extends LitElement {}`.
2814 pub class_local_name: String,
2815 /// Start byte offset of the registering class declaration (anchors the
2816 /// finding at the element, NOT line 1, since a `.ts` file can register
2817 /// several custom elements).
2818 pub span_start: u32,
2819}
2820
2821/// A key returned from a SvelteKit route `load()` function's terminal return
2822/// object literal. Harvested from `+page.{ts,server.ts,js,server.js}` files
2823/// exporting a `load` function. Consumed by the `unused-load-data-key` detector,
2824/// which flags a key read by no consumer. The span is stored as byte offsets
2825/// (not an `oxc_span::Span`) so the type round-trips through the bitcode cache
2826/// directly, mirroring `DiKeySite::span_start` / `ComponentEmit::span_start`.
2827#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2828pub struct LoadReturnKey {
2829 /// The returned-object property key name.
2830 pub name: String,
2831 /// Start byte offset of the key (anchors the finding).
2832 pub span_start: u32,
2833 /// End byte offset of the key.
2834 pub span_end: u32,
2835}
2836
2837/// The syntactic shape of an identified React component definition. Drives the
2838/// abstain ladder later phases apply: a `forwardRef` / `memo` wrapper whose
2839/// props come from an imported interface fallow cannot resolve must abstain
2840/// (ADR-001), not guess.
2841#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2842pub enum ComponentFunctionKind {
2843 /// A `function Foo() { return <.../> }` declaration.
2844 FnDecl,
2845 /// A `const Foo = () => <.../>` arrow (or function-expression) binding.
2846 Arrow,
2847 /// A `const Foo = forwardRef((props, ref) => <.../>)` wrapper.
2848 ForwardRefWrapper,
2849 /// A `const Foo = memo((props) => <.../>)` wrapper.
2850 MemoWrapper,
2851}
2852
2853/// An identified React component: a function/arrow whose body returns JSX.
2854/// Captured by `visit_jsx_element`'s enclosing-component tracking. The
2855/// `unused-component-prop` (React arm) and complexity-fold phases consume this;
2856/// the abstain flags keep zero-FP on the cases ADR-001 cannot resolve.
2857#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2858pub struct ComponentFunction {
2859 /// The component name (the binding or declaration identifier).
2860 pub name: String,
2861 /// Start byte offset of the component definition (anchors findings).
2862 pub span_start: u32,
2863 /// The syntactic shape of the definition.
2864 pub kind: ComponentFunctionKind,
2865 /// Whether the component is exported from its module (a named export, a
2866 /// `export default`, or re-exported in the same module). Public-API
2867 /// components abstain in the prop phase.
2868 pub is_exported: bool,
2869 /// `true` when the component's props are not statically harvestable: a
2870 /// rest/spread in the signature (`{ ...rest }`), props passed wholesale to a
2871 /// hook/helper, or a `forwardRef` / `memo` wrapper whose props come from an
2872 /// imported interface generic fallow cannot resolve (ADR-001). The prop
2873 /// phase abstains on the whole component when set.
2874 pub has_unharvestable_props: bool,
2875 /// `true` when the component body calls `cloneElement` / `React.cloneElement`.
2876 /// `cloneElement` injects props by reflection, so the static forward-set is
2877 /// incomplete; the prop-drilling phase abstains on any chain through this
2878 /// component (ADR-001, zero-FP).
2879 pub uses_clone_element: bool,
2880 /// `true` when the component renders a `*.Provider` member-expression tag
2881 /// (`<FooContext.Provider>`). A context provider in the subtree means the
2882 /// drilling may be a deliberate non-context choice (or the prop is about to
2883 /// be provided); the prop-drilling phase downgrades/abstains.
2884 pub renders_provider: bool,
2885 /// `true` when the component passes a function as a child render value
2886 /// (render-props / children-as-function: `<Foo>{() => ...}</Foo>` or
2887 /// `<Foo render={() => ...}/>`). The forwarded shape is dynamic; the
2888 /// prop-drilling phase abstains on chains through this component.
2889 pub has_children_as_function: bool,
2890 /// `true` when the component body is pure structural indirection: a single
2891 /// statement returning exactly one capitalized/member-expression JSX element
2892 /// (no host wrapper, no extra children, optionally a fragment wrapping a
2893 /// single element) that forwards props via a bare spread of the component's
2894 /// own props binding / rest local (`<Child {...props}/>`), with NO named
2895 /// attributes alongside the spread and NO self-render. The cross-component
2896 /// `thin-wrapper` phase joins this with hook-density / cyclomatic checks and
2897 /// the resolved single render edge to flag a component that is a candidate
2898 /// for inlining. Computed from the component's own AST only, so it caches
2899 /// byte-identity-safe (ADR-001).
2900 pub is_pure_passthrough: bool,
2901}
2902
2903/// The kind of a React hook call. `Custom` covers any `use*`-named call that is
2904/// not one of the built-in hooks.
2905#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2906pub enum HookUseKind {
2907 /// `useState(...)`.
2908 UseState,
2909 /// `useEffect(...)`.
2910 UseEffect,
2911 /// `useMemo(...)`.
2912 UseMemo,
2913 /// `useCallback(...)`.
2914 UseCallback,
2915 /// Any other `use*`-named call (a custom hook).
2916 Custom,
2917}
2918
2919/// A React hook call site inside a component. Consumed by the complexity-fold
2920/// phase (hook density) and surfaced as descriptive hotspot context.
2921#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2922pub struct HookUse {
2923 /// The hook kind.
2924 pub kind: HookUseKind,
2925 /// The dependency-array arity, recorded ONLY when a literal array is present
2926 /// at the dependency-array position (`[a, b]` -> `Some(2)`, `[]` ->
2927 /// `Some(0)`). `None` when the call has no dependency array argument or the
2928 /// argument is not a literal array (ADR-001: do not guess).
2929 pub dep_array_arity: Option<u32>,
2930 /// Start byte offset of the hook call (anchors findings).
2931 pub span_start: u32,
2932 /// The enclosing component name (the top of the visitor's component stack
2933 /// when the hook call was recorded). Lets the descriptive per-component hook
2934 /// summary attribute hooks exactly even when a file declares several
2935 /// components. A hook recorded outside any component carries an empty string
2936 /// (the visitor only records hooks inside a component, so this is the
2937 /// rare top-level / unattributed case).
2938 pub component: String,
2939}
2940
2941/// A render edge: one component rendering another (a capitalized or
2942/// member-expression JSX tag). Captured at extraction time with the child's
2943/// written name; resolution of `child_component_name` to a `FileId`/export is
2944/// deferred to graph build via the existing import map.
2945#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2946pub struct RenderEdge {
2947 /// The name of the component that renders the child (the enclosing
2948 /// component). Empty when the JSX is not inside an identified component (a
2949 /// top-level render expression).
2950 pub parent_component: String,
2951 /// The rendered child component name as written (`Foo` or the full
2952 /// member-expression path `Foo.Bar`).
2953 pub child_component_name: String,
2954 /// The attribute (prop) names passed at the render site, in source order.
2955 pub attr_names: Vec<String>,
2956 /// `true` when the render site contains a JSX spread (`{...x}`), so the
2957 /// passed-prop set is not statically complete.
2958 pub has_spread: bool,
2959 /// The forwarded attributes at this render site: each pairs the child
2960 /// attribute NAME with the identifier ROOT of its value expression
2961 /// (`userName={user.name}` -> `{ attr: "userName", root: "user" }`;
2962 /// `value={x}` -> `{ attr: "value", root: "x" }`). ONLY plain identifier or
2963 /// member-root access values are recorded (`{x}`, `{x.y}`, `{x.y.z}`); a value
2964 /// that is a call, an arrow/function, a conditional, a JSX element, or any
2965 /// other complex expression is NOT recorded here (its root would not be a pure
2966 /// forward) and sets `has_complex_forward` instead. The prop-drilling chain
2967 /// walk uses this pairing to map "this component forwards prop P" to "the
2968 /// child receives it as attribute A".
2969 pub forward_attrs: Vec<ForwardAttr>,
2970 /// `true` when at least one attribute value at this render site is a complex
2971 /// expression (a call, an arrow/function render-prop, a conditional, a JSX
2972 /// element-as-prop, a template literal, etc.) whose identifier root was NOT
2973 /// recorded in `forward_attrs`. The prop-drilling phase abstains on a chain
2974 /// whose forwarded prop flows through such a value (ADR-001, zero-FP).
2975 pub has_complex_forward: bool,
2976}
2977
2978/// One forwarded JSX attribute: the child attribute name plus the identifier
2979/// root of its value expression. See [`RenderEdge::forward_attrs`].
2980#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2981pub struct ForwardAttr {
2982 /// The child attribute (prop) name as written (`userName`).
2983 pub attr: String,
2984 /// The identifier root of the attribute value expression (`user` for
2985 /// `userName={user.name}`).
2986 pub root: String,
2987}
2988
2989#[expect(
2990 clippy::trivially_copy_pass_by_ref,
2991 reason = "serde serialize_with requires &T"
2992)]
2993fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
2994 use serde::ser::SerializeMap;
2995 let mut map = serializer.serialize_map(Some(2))?;
2996 map.serialize_entry("start", &span.start)?;
2997 map.serialize_entry("end", &span.end)?;
2998 map.end()
2999}
3000
3001/// Export identifier.
3002#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
3003pub enum ExportName {
3004 /// A named export (e.g., `export const foo`).
3005 Named(String),
3006 /// The default export.
3007 Default,
3008}
3009
3010impl ExportName {
3011 /// Compare against a string without allocating (avoids `to_string()`).
3012 #[must_use]
3013 pub fn matches_str(&self, s: &str) -> bool {
3014 match self {
3015 Self::Named(n) => n == s,
3016 Self::Default => s == "default",
3017 }
3018 }
3019}
3020
3021impl std::fmt::Display for ExportName {
3022 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3023 match self {
3024 Self::Named(n) => write!(f, "{n}"),
3025 Self::Default => write!(f, "default"),
3026 }
3027 }
3028}
3029
3030/// An import declaration.
3031#[derive(Debug, Clone)]
3032pub struct ImportInfo {
3033 /// The import specifier (e.g., `./utils` or `react`).
3034 pub source: String,
3035 /// How the symbol is imported (named, default, namespace, or side-effect).
3036 pub imported_name: ImportedName,
3037 /// The local binding name in the importing module.
3038 pub local_name: String,
3039 /// Whether this is a type-only import (`import type`).
3040 pub is_type_only: bool,
3041 /// Whether this whole-module import forwards type meanings only.
3042 ///
3043 /// Set for `export type *` and `export type * as ns` inside a
3044 /// `declare module '...'` body (issue #2375). Those forms record the same
3045 /// bindingless whole-module shape the plain ambient star records
3046 /// (issue #2357), but the star they stand for erases every value meaning,
3047 /// so the graph credits the target's star surface in the type namespace
3048 /// alone. Every other import leaves this false: `is_type_only` already
3049 /// decides their namespace on its own.
3050 pub is_type_only_star: bool,
3051 /// Whether this import originated from a CSS-context.
3052 pub from_style: bool,
3053 /// Source span of the import declaration.
3054 pub span: Span,
3055 /// Span of the source string literal used by the LSP to highlight the specifier.
3056 pub source_span: Span,
3057}
3058
3059/// How a symbol is imported.
3060#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3061pub enum ImportedName {
3062 /// A named import (e.g., `import { foo }`).
3063 Named(String),
3064 /// A default import (e.g., `import React`).
3065 Default,
3066 /// A namespace import (e.g., `import * as utils`).
3067 Namespace,
3068 /// A side-effect import (e.g., `import './styles.css'`).
3069 SideEffect,
3070}
3071
3072#[cfg(target_pointer_width = "64")]
3073const _: () = assert!(std::mem::size_of::<ExportInfo>() == 136);
3074#[cfg(target_pointer_width = "64")]
3075const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
3076#[cfg(target_pointer_width = "64")]
3077const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
3078#[cfg(target_pointer_width = "64")]
3079const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
3080#[cfg(target_pointer_width = "64")]
3081const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
3082#[cfg(target_pointer_width = "64")]
3083const _: () = assert!(std::mem::size_of::<SemanticFact>() == 96);
3084#[cfg(target_pointer_width = "64")]
3085const _: () = assert!(std::mem::size_of::<SinkSite>() == 216);
3086#[cfg(target_pointer_width = "64")]
3087const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 1336);
3088#[cfg(target_pointer_width = "64")]
3089const _: () = assert!(std::mem::size_of::<TypeMemberTypeEntry>() == 72);
3090
3091/// A re-export declaration.
3092#[derive(Debug, Clone)]
3093pub struct ReExportInfo {
3094 /// The module being re-exported from.
3095 pub source: String,
3096 /// The name imported from the source module (or `*` for star re-exports).
3097 pub imported_name: String,
3098 /// The name exported from this module.
3099 pub exported_name: String,
3100 /// Whether this is a type-only re-export.
3101 pub is_type_only: bool,
3102 /// Source span of the re-export declaration on this module.
3103 pub span: oxc_span::Span,
3104 /// Span of the whole re-export statement. A multi-binding statement
3105 /// yields one `ReExportInfo` per binding, each with a per-binding
3106 /// `span`; this field lets consumers reason about the enclosing
3107 /// statement (e.g. suppression coverage). Empty (`start == end`) for
3108 /// synthesized re-exports that have no single owning statement.
3109 pub statement_span: oxc_span::Span,
3110 /// Span of the source string literal (the specifier in quotes), used to
3111 /// anchor unresolved-import findings on the specifier. Empty
3112 /// (`start == end`) when no literal exists in the statement.
3113 pub source_span: oxc_span::Span,
3114}
3115
3116/// A dynamic `import()` call.
3117#[derive(Debug, Clone)]
3118pub struct DynamicImportInfo {
3119 /// The import specifier.
3120 pub source: String,
3121 /// Source span of the `import()` expression.
3122 pub span: Span,
3123 /// Names destructured from the dynamic import result.
3124 /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
3125 /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
3126 pub destructured_names: Vec<String>,
3127 /// The local variable name for `const x = await import(...)`.
3128 /// Used for namespace import narrowing via member access tracking.
3129 pub local_name: Option<String>,
3130 /// True when this dynamic import was synthesised by fallow rather than appearing in user source.
3131 pub is_speculative: bool,
3132}
3133
3134/// A `require()` call.
3135#[derive(Debug, Clone)]
3136pub struct RequireCallInfo {
3137 /// The require specifier.
3138 pub source: String,
3139 /// Source span of the `require()` call.
3140 pub span: Span,
3141 /// Source span of the specifier string-literal argument (including its
3142 /// quotes), e.g. the `'./x'` in `require('./x')`. Used to anchor an
3143 /// `unresolved-import` diagnostic squiggly under the specifier rather than
3144 /// the `require` keyword. `Span::default()` when the argument is not a
3145 /// plain string literal.
3146 pub source_span: Span,
3147 /// Names destructured from the `require()` result.
3148 pub destructured_names: Vec<String>,
3149 /// The local variable name for `const x = require(...)`.
3150 pub local_name: Option<String>,
3151 /// `true` for `import type X = require('...')`, the one require spelling
3152 /// TypeScript erases entirely: the emitted JavaScript contains no
3153 /// `require` call, so the target is a type-space reference and never a
3154 /// runtime dependency. Always `false` for `const x = require(...)`, which
3155 /// has no type-only spelling. Read by dependency classification so a
3156 /// type-only devDependency is not reported as production usage.
3157 pub is_type_only: bool,
3158}
3159
3160/// Result of parsing all files, including incremental cache statistics.
3161pub struct ParseResult {
3162 /// Extracted module information for all successfully parsed files.
3163 pub modules: Vec<ModuleInfo>,
3164 /// Files discovered with stable IDs but unreadable by the parser.
3165 pub read_failures: Vec<SourceReadFailure>,
3166 /// Number of files whose parse results were loaded from cache (unchanged).
3167 pub cache_hits: usize,
3168 /// Number of files that required a full parse (new or changed).
3169 pub cache_misses: usize,
3170 /// Summed wall-clock time of the actual AST parses across all rayon workers.
3171 pub parse_cpu_ms: f64,
3172}
3173
3174/// A discovered source that could not be read as UTF-8 text.
3175#[derive(Debug, Clone, PartialEq, Eq)]
3176pub struct SourceReadFailure {
3177 /// Stable discovery identity retained even though no module was produced.
3178 pub file_id: FileId,
3179 /// Absolute discovered source path.
3180 pub path: PathBuf,
3181 /// Underlying filesystem or UTF-8 decoding error.
3182 pub error: String,
3183}
3184
3185#[cfg(test)]
3186mod tests {
3187 use super::*;
3188
3189 fn span() -> Span {
3190 Span::new(0, 1)
3191 }
3192
3193 macro_rules! assert_released {
3194 ($values:expr) => {{
3195 assert!($values.is_empty());
3196 }};
3197 }
3198
3199 #[test]
3200 fn public_env_var_includes_public_ci_metadata() {
3201 for name in ["TAG_REF", "GITHUB_SHA", "CI_COMMIT_BRANCH", "APP_MODE"] {
3202 assert!(is_public_env_var(name), "{name} should be public metadata");
3203 }
3204 }
3205
3206 #[test]
3207 fn public_env_var_keeps_secret_shaped_names_source_backed() {
3208 for name in ["GITHUB_TOKEN", "REFRESH_TOKEN", "API_KEY", "SECRET_SHA"] {
3209 assert!(
3210 !is_public_env_var(name),
3211 "{name} should remain secret-shaped"
3212 );
3213 }
3214 }
3215
3216 #[test]
3217 fn ordinary_access_helpers_keep_source_accesses() {
3218 let member_accesses = vec![
3219 MemberAccess {
3220 object: "this".to_string(),
3221 member: "render".to_string(),
3222 },
3223 MemberAccess {
3224 object: "service".to_string(),
3225 member: "run".to_string(),
3226 },
3227 ];
3228 let ordinary = SemanticFactView::new(&[], &member_accesses)
3229 .ordinary_member_accesses()
3230 .map(|access| (access.object.as_str(), access.member.as_str()))
3231 .collect::<Vec<_>>();
3232
3233 assert_eq!(ordinary, vec![("this", "render"), ("service", "run")]);
3234
3235 let whole_object_uses = vec!["model".to_string(), "service".to_string()];
3236
3237 assert_eq!(
3238 ordinary_whole_object_uses(&whole_object_uses).collect::<Vec<_>>(),
3239 vec!["model", "service"]
3240 );
3241 }
3242
3243 #[test]
3244 fn angular_template_member_names_use_typed_facts() {
3245 let mut module = minimal_module_info();
3246 push_semantic_fact(
3247 &mut module,
3248 SemanticFact::AngularTemplateMemberAccess(AngularTemplateMemberAccessFact {
3249 member: "typed".to_string(),
3250 }),
3251 );
3252
3253 let names: Vec<&str> = angular_template_member_names(&module).collect();
3254
3255 assert_eq!(names, vec!["typed"]);
3256 assert!(has_angular_template_members(&module));
3257 }
3258
3259 #[test]
3260 fn angular_this_spread_uses_typed_fact() {
3261 let mut typed = minimal_module_info();
3262 push_semantic_fact(
3263 &mut typed,
3264 SemanticFact::AngularThisSpread(AngularThisSpreadFact),
3265 );
3266
3267 assert!(has_angular_this_spread(&typed));
3268 assert!(!has_angular_this_spread(&minimal_module_info()));
3269 }
3270
3271 #[test]
3272 fn semantic_fact_view_iterates_typed_facts() {
3273 let mut module = minimal_module_info();
3274 push_semantic_fact(
3275 &mut module,
3276 SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3277 callee_object: "Svc".to_string(),
3278 callee_method: "make".to_string(),
3279 member: "run".to_string(),
3280 }),
3281 );
3282
3283 let facts = SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3284 .facts()
3285 .collect::<Vec<_>>();
3286
3287 assert_eq!(
3288 facts[0],
3289 &SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3290 callee_object: "Svc".to_string(),
3291 callee_method: "make".to_string(),
3292 member: "run".to_string(),
3293 })
3294 );
3295 }
3296
3297 #[test]
3298 fn typed_fact_helpers_collect_each_family() {
3299 let mut module = minimal_module_info();
3300 push_semantic_fact(
3301 &mut module,
3302 SemanticFact::InstanceExportBinding(InstanceExportBindingFact {
3303 export_name: "exported".to_string(),
3304 target_name: "target".to_string(),
3305 }),
3306 );
3307 push_semantic_fact(
3308 &mut module,
3309 SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3310 callee_object: "Svc".to_string(),
3311 callee_method: "create".to_string(),
3312 member: "run".to_string(),
3313 }),
3314 );
3315 push_semantic_fact(
3316 &mut module,
3317 SemanticFact::FluentChainMemberAccess(FluentChainMemberAccessFact {
3318 root_object: "Builder".to_string(),
3319 root_method: "start".to_string(),
3320 chain: vec!["next".to_string()],
3321 member: "value".to_string(),
3322 }),
3323 );
3324 push_semantic_fact(
3325 &mut module,
3326 SemanticFact::FluentChainNewMemberAccess(FluentChainNewMemberAccessFact {
3327 class_name: "Builder".to_string(),
3328 chain: vec!["next".to_string(), "finish".to_string()],
3329 member: "done".to_string(),
3330 }),
3331 );
3332
3333 assert_eq!(
3334 SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3335 .instance_export_bindings(),
3336 vec![InstanceExportBindingFact {
3337 export_name: "exported".to_string(),
3338 target_name: "target".to_string(),
3339 }]
3340 );
3341 assert_eq!(
3342 SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3343 .factory_call_member_accesses(),
3344 vec![FactoryCallMemberAccessFact {
3345 callee_object: "Svc".to_string(),
3346 callee_method: "create".to_string(),
3347 member: "run".to_string(),
3348 }]
3349 );
3350 assert_eq!(
3351 SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3352 .fluent_chain_member_accesses(),
3353 vec![FluentChainMemberAccessFact {
3354 root_object: "Builder".to_string(),
3355 root_method: "start".to_string(),
3356 chain: vec!["next".to_string()],
3357 member: "value".to_string(),
3358 }]
3359 );
3360 assert_eq!(
3361 SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3362 .fluent_chain_new_member_accesses(),
3363 vec![FluentChainNewMemberAccessFact {
3364 class_name: "Builder".to_string(),
3365 chain: vec!["next".to_string(), "finish".to_string()],
3366 member: "done".to_string(),
3367 }]
3368 );
3369 }
3370
3371 #[test]
3372 fn semantic_fact_view_exposes_typed_first_contract() {
3373 let mut module = minimal_module_info();
3374 push_semantic_fact(
3375 &mut module,
3376 SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3377 callee_object: "Svc".to_string(),
3378 callee_method: "create".to_string(),
3379 member: "run".to_string(),
3380 }),
3381 );
3382 push_semantic_fact(
3383 &mut module,
3384 SemanticFact::PlaywrightFixtureUse(PlaywrightFixtureUseFact {
3385 test_name: "test".to_string(),
3386 fixture_name: "page".to_string(),
3387 member: "goto".to_string(),
3388 }),
3389 );
3390 push_semantic_fact(
3391 &mut module,
3392 SemanticFact::InstanceExportBinding(InstanceExportBindingFact {
3393 export_name: "exported".to_string(),
3394 target_name: "target".to_string(),
3395 }),
3396 );
3397
3398 let view = SemanticFactView::new(&module.semantic_facts, &module.member_accesses);
3399
3400 assert_eq!(
3401 view.factory_call_member_accesses(),
3402 vec![FactoryCallMemberAccessFact {
3403 callee_object: "Svc".to_string(),
3404 callee_method: "create".to_string(),
3405 member: "run".to_string(),
3406 }]
3407 );
3408 assert_eq!(
3409 view.playwright_fixture_uses(),
3410 vec![PlaywrightFixtureUseFact {
3411 test_name: "test".to_string(),
3412 fixture_name: "page".to_string(),
3413 member: "goto".to_string(),
3414 }]
3415 );
3416 assert_eq!(
3417 view.instance_export_bindings(),
3418 vec![InstanceExportBindingFact {
3419 export_name: "exported".to_string(),
3420 target_name: "target".to_string(),
3421 }]
3422 );
3423 }
3424
3425 #[test]
3426 fn playwright_fixture_fact_helpers_select_each_fact_family() {
3427 let mut module = minimal_module_info();
3428 push_semantic_fact(
3429 &mut module,
3430 SemanticFact::PlaywrightFixtureUse(PlaywrightFixtureUseFact {
3431 test_name: "test".to_string(),
3432 fixture_name: "page".to_string(),
3433 member: "goto".to_string(),
3434 }),
3435 );
3436 push_semantic_fact(
3437 &mut module,
3438 SemanticFact::PlaywrightFixtureDefinition(PlaywrightFixtureDefinitionFact {
3439 test_name: "test".to_string(),
3440 fixture_name: "adminPage".to_string(),
3441 type_name: "AdminPage".to_string(),
3442 }),
3443 );
3444 push_semantic_fact(
3445 &mut module,
3446 SemanticFact::PlaywrightFixtureAlias(PlaywrightFixtureAliasFact {
3447 test_name: "mergedTest".to_string(),
3448 base_name: "test".to_string(),
3449 }),
3450 );
3451 push_semantic_fact(
3452 &mut module,
3453 SemanticFact::PlaywrightFixtureType(PlaywrightFixtureTypeFact {
3454 alias_name: "Pages".to_string(),
3455 fixture_name: "adminPage".to_string(),
3456 type_name: "AdminPage".to_string(),
3457 }),
3458 );
3459
3460 assert_eq!(
3461 playwright_fixture_use_facts(&module.semantic_facts)
3462 .map(|fact| fact.member.as_str())
3463 .collect::<Vec<_>>(),
3464 vec!["goto"]
3465 );
3466 assert_eq!(
3467 playwright_fixture_definition_facts(&module.semantic_facts)
3468 .map(|fact| fact.type_name.as_str())
3469 .collect::<Vec<_>>(),
3470 vec!["AdminPage"]
3471 );
3472 assert_eq!(
3473 playwright_fixture_alias_facts(&module.semantic_facts)
3474 .map(|fact| fact.base_name.as_str())
3475 .collect::<Vec<_>>(),
3476 vec!["test"]
3477 );
3478 assert_eq!(
3479 playwright_fixture_type_facts(&module.semantic_facts)
3480 .map(|fact| fact.fixture_name.as_str())
3481 .collect::<Vec<_>>(),
3482 vec!["adminPage"]
3483 );
3484 }
3485
3486 #[test]
3487 fn line_offsets_empty_string() {
3488 assert_eq!(compute_line_offsets(""), vec![0]);
3489 }
3490
3491 #[test]
3492 #[expect(
3493 clippy::too_many_lines,
3494 reason = "exhaustive field-by-field construction + release assertions for every ModuleInfo field"
3495 )]
3496 fn release_resolution_payload_drops_copied_vectors_only() {
3497 let mut module = ModuleInfo {
3498 file_id: FileId(7),
3499 exports: vec![ExportInfo {
3500 name: ExportName::Named("kept".to_string()),
3501 local_name: None,
3502 is_type_only: false,
3503 is_side_effect_used: false,
3504 visibility: VisibilityTag::None,
3505 expected_unused_reason: None,
3506 span: span(),
3507 members: Vec::new(),
3508 super_class: None,
3509 }]
3510 .into(),
3511 imports: vec![ImportInfo {
3512 source: "node:child_process".to_string(),
3513 imported_name: ImportedName::Default,
3514 local_name: "childProcess".to_string(),
3515 is_type_only: false,
3516 is_type_only_star: false,
3517 from_style: false,
3518 span: span(),
3519 source_span: span(),
3520 }],
3521 re_exports: vec![ReExportInfo {
3522 source: "./kept".to_string(),
3523 imported_name: "kept".to_string(),
3524 exported_name: "kept".to_string(),
3525 is_type_only: false,
3526 span: span(),
3527 statement_span: span(),
3528 source_span: span(),
3529 }],
3530 dynamic_imports: vec![DynamicImportInfo {
3531 source: "./dynamic".to_string(),
3532 span: span(),
3533 destructured_names: vec!["value".to_string()],
3534 local_name: None,
3535 is_speculative: false,
3536 }],
3537 dynamic_import_patterns: vec![DynamicImportPattern {
3538 prefix: "./pages/".to_string(),
3539 suffix: Some(".tsx".to_string()),
3540 span: span(),
3541 mechanism: ModuleLoadMechanism::EsModule,
3542 }],
3543 require_calls: vec![RequireCallInfo {
3544 source: "./required".to_string(),
3545 span: span(),
3546 source_span: span(),
3547 destructured_names: Vec::new(),
3548 local_name: Some("required".to_string()),
3549 is_type_only: false,
3550 }],
3551 package_path_references: vec!["react".to_string()].into(),
3552 member_accesses: vec![MemberAccess {
3553 object: "Status".to_string(),
3554 member: "Active".to_string(),
3555 }]
3556 .into(),
3557 semantic_facts: std::sync::Arc::default(),
3558 whole_object_uses: vec!["Status".to_string()].into(),
3559 has_cjs_exports: true,
3560 has_angular_component_template_url: true,
3561 content_hash: 42,
3562 suppressions: Vec::new(),
3563 unknown_suppression_kinds: Vec::new(),
3564 unused_import_bindings: vec!["unused".to_string()],
3565 type_referenced_import_bindings: vec!["TypeOnly".to_string()],
3566 value_referenced_import_bindings: vec!["Value".to_string()],
3567 line_offsets: vec![0, 8],
3568 complexity: vec![FunctionComplexity {
3569 name: "work".to_string(),
3570 is_private_member: false,
3571 line: 1,
3572 col: 0,
3573 cyclomatic: 2,
3574 cognitive: 3,
3575 line_count: 4,
3576 param_count: 1,
3577 react_hook_count: 0,
3578 react_jsx_max_depth: 0,
3579 react_prop_count: 0,
3580 source_hash: Some("hash".to_string()),
3581 contributions: Vec::new(),
3582 }],
3583 flag_uses: vec![FlagUse {
3584 flag_name: "FEATURE_X".to_string(),
3585 kind: FlagUseKind::EnvVar,
3586 line: 1,
3587 col: 0,
3588 guard_span_start: None,
3589 guard_span_end: None,
3590 sdk_name: None,
3591 }],
3592 class_heritage: vec![ClassHeritageInfo {
3593 export_name: "Child".to_string(),
3594 super_class: Some("Parent".to_string()),
3595 implements: vec!["Contract".to_string()],
3596 type_parameters: Vec::new(),
3597 instance_bindings: Vec::new(),
3598 super_class_type_args: Vec::new(),
3599 generic_instance_bindings: Vec::new(),
3600 }],
3601 exported_factory_returns: std::sync::Arc::from([FactoryReturnExport {
3602 export_name: "useApi".to_string(),
3603 class_local_name: "RESTApi".to_string(),
3604 }]),
3605 exported_factory_return_object_shapes: std::sync::Arc::from([
3606 FactoryReturnObjectShapeExport {
3607 export_name: "createUi".to_string(),
3608 properties: Box::from([FactoryReturnObjectProperty {
3609 property_path: "orders".to_string(),
3610 class_local_name: "OrdersPage".to_string(),
3611 }]),
3612 },
3613 ]),
3614 type_member_types: std::sync::Arc::from([TypeMemberTypeEntry {
3615 type_name: "Opts".to_string(),
3616 property: "c".to_string(),
3617 property_type: "OptDep".to_string(),
3618 }]),
3619 injection_tokens: vec![("TOKEN".to_string(), "Contract".to_string())],
3620 local_type_declarations: vec![LocalTypeDeclaration {
3621 name: "Contract".to_string(),
3622 span: span(),
3623 }],
3624 public_signature_type_references: vec![PublicSignatureTypeReference {
3625 export_name: "kept".to_string(),
3626 type_name: "Contract".to_string(),
3627 span: span(),
3628 }],
3629 namespace_object_aliases: vec![NamespaceObjectAlias {
3630 via_export_name: "api".to_string(),
3631 suffix: "read".to_string(),
3632 namespace_local: "ns".to_string(),
3633 }],
3634 iconify_prefixes: vec!["hero".to_string()],
3635 iconify_icon_names: vec!["hero-home".to_string()],
3636 auto_import_candidates: vec!["useState".to_string()],
3637 directives: vec!["use client".to_string()],
3638 client_only_dynamic_import_spans: Vec::new(),
3639 security_sinks: Vec::new(),
3640 security_sinks_skipped: 1,
3641 security_unresolved_callee_sites: Vec::new(),
3642 tainted_bindings: Vec::new(),
3643 sanitized_sink_args: Vec::new(),
3644 security_control_sites: Vec::new(),
3645 callee_uses: Vec::new(),
3646 misplaced_directives: Vec::new(),
3647 inline_server_action_exports: Vec::new(),
3648 di_key_sites: Vec::new(),
3649 has_dynamic_provide: false,
3650 referenced_import_bindings: Vec::new(),
3651 component_props: Vec::new(),
3652 has_props_attrs_fallthrough: false,
3653 has_define_expose: false,
3654 has_define_model: false,
3655 has_unharvestable_props: false,
3656 component_emits: Vec::new(),
3657 angular_inputs: Vec::new(),
3658 angular_outputs: Vec::new(),
3659 angular_component_selectors: Vec::new(),
3660 registered_custom_elements: Vec::new(),
3661 used_custom_element_tags: Vec::new(),
3662 angular_used_selectors: Vec::new(),
3663 angular_entry_component_refs: Vec::new(),
3664 has_dynamic_component_render: false,
3665 has_unharvestable_emits: false,
3666 has_dynamic_emit: false,
3667 has_emit_whole_object_use: false,
3668 load_return_keys: Vec::new(),
3669 has_unharvestable_load: false,
3670 has_load_data_whole_use: false,
3671 has_page_data_store_whole_use: false,
3672 has_route_loader_data_whole_use: false,
3673 component_functions: Vec::new(),
3674 react_props: Vec::new(),
3675 hook_uses: Vec::new(),
3676 render_edges: Vec::new(),
3677 svelte_dispatched_events: Vec::new(),
3678 svelte_listened_events: Vec::new(),
3679 has_dynamic_dispatch: false,
3680 };
3681
3682 module.release_resolution_payload();
3683
3684 assert_eq!(module.file_id, FileId(7));
3685 assert_eq!(module.content_hash, 42);
3686 assert_eq!(module.line_offsets, vec![0, 8]);
3687 assert_eq!(module.imports.len(), 1);
3688 assert_eq!(module.exports.len(), 1);
3689 assert_eq!(module.re_exports.len(), 1);
3690 assert_eq!(module.dynamic_import_patterns.len(), 1);
3691 assert_eq!(module.member_accesses.len(), 1);
3692 assert_eq!(module.complexity.len(), 1);
3693 assert_eq!(module.flag_uses.len(), 1);
3694 assert_eq!(module.class_heritage.len(), 1);
3695 assert_eq!(module.exported_factory_returns.len(), 1);
3696 assert_eq!(module.injection_tokens.len(), 1);
3697 assert_eq!(module.local_type_declarations.len(), 1);
3698 assert_eq!(module.public_signature_type_references.len(), 1);
3699 assert_eq!(module.iconify_prefixes.len(), 1);
3700 assert_eq!(module.iconify_icon_names.len(), 1);
3701 assert_eq!(module.directives.len(), 1);
3702 assert_eq!(module.security_sinks_skipped, 1);
3703 assert_released!(module.dynamic_imports);
3704 assert_released!(module.require_calls);
3705 assert_released!(module.package_path_references);
3706 assert_released!(module.whole_object_uses);
3707 assert_released!(module.unused_import_bindings);
3708 assert_released!(module.type_referenced_import_bindings);
3709 assert_released!(module.value_referenced_import_bindings);
3710 assert_released!(module.namespace_object_aliases);
3711 assert_released!(module.auto_import_candidates);
3712 assert_eq!(
3713 module.referenced_import_bindings,
3714 vec!["childProcess".to_string()]
3715 );
3716 }
3717
3718 #[test]
3719 fn sink_shape_bitcode_roundtrip() {
3720 for shape in [
3721 SinkShape::Call,
3722 SinkShape::MemberCall,
3723 SinkShape::MemberAssign,
3724 SinkShape::TaggedTemplate,
3725 SinkShape::JsxAttr,
3726 SinkShape::NewExpression,
3727 SinkShape::SecretLiteral,
3728 ] {
3729 let encoded = bitcode::encode(&shape);
3730 let decoded: SinkShape = bitcode::decode(&encoded).expect("decode sink shape");
3731 assert_eq!(shape, decoded);
3732 }
3733 }
3734
3735 #[test]
3736 fn sink_arg_kind_bitcode_roundtrip() {
3737 for kind in [
3738 SinkArgKind::TemplateWithSubst,
3739 SinkArgKind::Concat,
3740 SinkArgKind::Object,
3741 SinkArgKind::Call,
3742 SinkArgKind::Literal,
3743 SinkArgKind::NoArg,
3744 SinkArgKind::Other,
3745 ] {
3746 let encoded = bitcode::encode(&kind);
3747 let decoded: SinkArgKind = bitcode::decode(&encoded).expect("decode sink arg kind");
3748 assert_eq!(kind, decoded);
3749 }
3750 }
3751
3752 #[test]
3753 fn security_url_shape_bitcode_roundtrip() {
3754 for shape in [
3755 SecurityUrlShape::FixedOriginDynamicPath,
3756 SecurityUrlShape::DynamicOrigin,
3757 ] {
3758 let encoded = bitcode::encode(&shape);
3759 let decoded: SecurityUrlShape =
3760 bitcode::decode(&encoded).expect("decode security url shape");
3761 assert_eq!(shape, decoded);
3762 }
3763 }
3764
3765 #[test]
3766 fn sink_site_bitcode_roundtrip() {
3767 let site = SinkSite {
3768 sink_shape: SinkShape::MemberAssign,
3769 callee_path: "el.innerHTML".to_string(),
3770 arg_index: 0,
3771 arg_is_non_literal: true,
3772 arg_kind: SinkArgKind::Other,
3773 arg_literal: Some(SinkLiteralValue::Integer(511)),
3774 regex_pattern: None,
3775 object_properties: vec![SinkObjectProperty {
3776 key: "origin".to_string(),
3777 value: SinkLiteralValue::String("*".to_string()),
3778 }],
3779 object_property_keys: vec!["origin".to_string()],
3780 object_property_keys_complete: true,
3781 arg_idents: vec!["userInput".to_string()],
3782 arg_source_paths: vec!["req.body.email".to_string(), "req.body".to_string()],
3783 span_start: 10,
3784 span_end: 20,
3785 url_arg_literal: Some("https://api.example.com".to_string()),
3786 url_shape: Some(SecurityUrlShape::FixedOriginDynamicPath),
3787 };
3788 let encoded = bitcode::encode(&site);
3789 let decoded: SinkSite = bitcode::decode(&encoded).expect("decode sink site");
3790 assert_eq!(decoded.sink_shape, site.sink_shape);
3791 assert_eq!(decoded.callee_path, site.callee_path);
3792 assert_eq!(decoded.arg_index, site.arg_index);
3793 assert_eq!(decoded.arg_is_non_literal, site.arg_is_non_literal);
3794 assert_eq!(decoded.arg_kind, site.arg_kind);
3795 assert_eq!(decoded.arg_literal, site.arg_literal);
3796 assert_eq!(decoded.object_properties, site.object_properties);
3797 assert_eq!(decoded.object_property_keys, site.object_property_keys);
3798 assert_eq!(
3799 decoded.object_property_keys_complete,
3800 site.object_property_keys_complete
3801 );
3802 assert_eq!(decoded.arg_idents, site.arg_idents);
3803 assert_eq!(decoded.arg_source_paths, site.arg_source_paths);
3804 assert_eq!(decoded.url_shape, site.url_shape);
3805 assert_eq!(decoded.span(), site.span());
3806 }
3807
3808 #[test]
3809 fn line_offsets_single_line_no_newline() {
3810 assert_eq!(compute_line_offsets("hello"), vec![0]);
3811 }
3812
3813 #[test]
3814 fn line_offsets_single_line_with_newline() {
3815 assert_eq!(compute_line_offsets("hello\n"), vec![0, 6]);
3816 }
3817
3818 #[test]
3819 fn line_offsets_multiple_lines() {
3820 assert_eq!(compute_line_offsets("abc\ndef\nghi"), vec![0, 4, 8]);
3821 }
3822
3823 #[test]
3824 fn line_offsets_trailing_newline() {
3825 assert_eq!(compute_line_offsets("abc\ndef\n"), vec![0, 4, 8]);
3826 }
3827
3828 #[test]
3829 fn line_offsets_consecutive_newlines() {
3830 assert_eq!(compute_line_offsets("\n\n\n"), vec![0, 1, 2, 3]);
3831 }
3832
3833 #[test]
3834 fn line_offsets_multibyte_utf8() {
3835 assert_eq!(compute_line_offsets("á\n"), vec![0, 3]);
3836 }
3837
3838 #[test]
3839 fn line_col_offset_zero() {
3840 let offsets = compute_line_offsets("abc\ndef\nghi");
3841 let (line, col) = byte_offset_to_line_col(&offsets, 0);
3842 assert_eq!((line, col), (1, 0));
3843 }
3844
3845 #[test]
3846 fn line_col_middle_of_first_line() {
3847 let offsets = compute_line_offsets("abc\ndef\nghi");
3848 let (line, col) = byte_offset_to_line_col(&offsets, 2);
3849 assert_eq!((line, col), (1, 2));
3850 }
3851
3852 #[test]
3853 fn line_col_start_of_second_line() {
3854 let offsets = compute_line_offsets("abc\ndef\nghi");
3855 let (line, col) = byte_offset_to_line_col(&offsets, 4);
3856 assert_eq!((line, col), (2, 0));
3857 }
3858
3859 #[test]
3860 fn line_col_middle_of_second_line() {
3861 let offsets = compute_line_offsets("abc\ndef\nghi");
3862 let (line, col) = byte_offset_to_line_col(&offsets, 5);
3863 assert_eq!((line, col), (2, 1));
3864 }
3865
3866 #[test]
3867 fn line_col_start_of_third_line() {
3868 let offsets = compute_line_offsets("abc\ndef\nghi");
3869 let (line, col) = byte_offset_to_line_col(&offsets, 8);
3870 assert_eq!((line, col), (3, 0));
3871 }
3872
3873 #[test]
3874 fn line_col_end_of_file() {
3875 let offsets = compute_line_offsets("abc\ndef\nghi");
3876 let (line, col) = byte_offset_to_line_col(&offsets, 10);
3877 assert_eq!((line, col), (3, 2));
3878 }
3879
3880 #[test]
3881 fn line_col_single_line() {
3882 let offsets = compute_line_offsets("hello");
3883 let (line, col) = byte_offset_to_line_col(&offsets, 3);
3884 assert_eq!((line, col), (1, 3));
3885 }
3886
3887 #[test]
3888 fn line_col_at_newline_byte() {
3889 let offsets = compute_line_offsets("abc\ndef");
3890 let (line, col) = byte_offset_to_line_col(&offsets, 3);
3891 assert_eq!((line, col), (1, 3));
3892 }
3893
3894 #[test]
3895 fn export_name_matches_str_named() {
3896 let name = ExportName::Named("foo".to_string());
3897 assert!(name.matches_str("foo"));
3898 assert!(!name.matches_str("bar"));
3899 assert!(!name.matches_str("default"));
3900 }
3901
3902 #[test]
3903 fn export_name_matches_str_default() {
3904 let name = ExportName::Default;
3905 assert!(name.matches_str("default"));
3906 assert!(!name.matches_str("foo"));
3907 }
3908
3909 #[test]
3910 fn export_name_display_named() {
3911 let name = ExportName::Named("myExport".to_string());
3912 assert_eq!(name.to_string(), "myExport");
3913 }
3914
3915 #[test]
3916 fn export_name_display_default() {
3917 let name = ExportName::Default;
3918 assert_eq!(name.to_string(), "default");
3919 }
3920
3921 #[test]
3922 fn export_name_equality_named() {
3923 let a = ExportName::Named("foo".to_string());
3924 let b = ExportName::Named("foo".to_string());
3925 let c = ExportName::Named("bar".to_string());
3926 assert_eq!(a, b);
3927 assert_ne!(a, c);
3928 }
3929
3930 #[test]
3931 fn export_name_equality_default() {
3932 let a = ExportName::Default;
3933 let b = ExportName::Default;
3934 assert_eq!(a, b);
3935 }
3936
3937 #[test]
3938 fn export_name_named_not_equal_to_default() {
3939 let named = ExportName::Named("default".to_string());
3940 let default = ExportName::Default;
3941 assert_ne!(named, default);
3942 }
3943
3944 #[test]
3945 fn export_name_hash_consistency() {
3946 use std::collections::hash_map::DefaultHasher;
3947 use std::hash::{Hash, Hasher};
3948
3949 let mut h1 = DefaultHasher::new();
3950 let mut h2 = DefaultHasher::new();
3951 ExportName::Named("foo".to_string()).hash(&mut h1);
3952 ExportName::Named("foo".to_string()).hash(&mut h2);
3953 assert_eq!(h1.finish(), h2.finish());
3954 }
3955
3956 #[test]
3957 fn export_name_matches_str_empty_string() {
3958 let name = ExportName::Named(String::new());
3959 assert!(name.matches_str(""));
3960 assert!(!name.matches_str("foo"));
3961 }
3962
3963 #[test]
3964 fn export_name_default_does_not_match_empty() {
3965 let name = ExportName::Default;
3966 assert!(!name.matches_str(""));
3967 }
3968
3969 #[test]
3970 fn imported_name_equality() {
3971 assert_eq!(
3972 ImportedName::Named("foo".to_string()),
3973 ImportedName::Named("foo".to_string())
3974 );
3975 assert_ne!(
3976 ImportedName::Named("foo".to_string()),
3977 ImportedName::Named("bar".to_string())
3978 );
3979 assert_eq!(ImportedName::Default, ImportedName::Default);
3980 assert_eq!(ImportedName::Namespace, ImportedName::Namespace);
3981 assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
3982 assert_ne!(ImportedName::Default, ImportedName::Namespace);
3983 assert_ne!(
3984 ImportedName::Named("default".to_string()),
3985 ImportedName::Default
3986 );
3987 }
3988
3989 #[test]
3990 fn member_kind_equality() {
3991 assert_eq!(MemberKind::EnumMember, MemberKind::EnumMember);
3992 assert_eq!(MemberKind::ClassMethod, MemberKind::ClassMethod);
3993 assert_eq!(MemberKind::ClassProperty, MemberKind::ClassProperty);
3994 assert_eq!(MemberKind::NamespaceMember, MemberKind::NamespaceMember);
3995 assert_ne!(MemberKind::EnumMember, MemberKind::ClassMethod);
3996 assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
3997 assert_ne!(MemberKind::NamespaceMember, MemberKind::EnumMember);
3998 }
3999
4000 #[test]
4001 fn member_kind_bitcode_roundtrip() {
4002 let kinds = [
4003 MemberKind::EnumMember,
4004 MemberKind::ClassMethod,
4005 MemberKind::ClassProperty,
4006 MemberKind::NamespaceMember,
4007 ];
4008 for kind in &kinds {
4009 let bytes = bitcode::encode(kind);
4010 let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
4011 assert_eq!(&decoded, kind);
4012 }
4013 }
4014
4015 #[test]
4016 fn member_access_bitcode_roundtrip() {
4017 let access = MemberAccess {
4018 object: "Status".to_string(),
4019 member: "Active".to_string(),
4020 };
4021 let bytes = bitcode::encode(&access);
4022 let decoded: MemberAccess = bitcode::decode(&bytes).unwrap();
4023 assert_eq!(decoded.object, "Status");
4024 assert_eq!(decoded.member, "Active");
4025 }
4026
4027 #[test]
4028 fn line_offsets_crlf_only_counts_lf() {
4029 let offsets = compute_line_offsets("ab\r\ncd");
4030 assert_eq!(offsets, vec![0, 4]);
4031 }
4032
4033 #[test]
4034 fn line_col_empty_file_offset_zero() {
4035 let offsets = compute_line_offsets("");
4036 let (line, col) = byte_offset_to_line_col(&offsets, 0);
4037 assert_eq!((line, col), (1, 0));
4038 }
4039
4040 // --- VisibilityTag ---
4041
4042 #[test]
4043 fn visibility_tag_default_is_none_variant() {
4044 assert_eq!(VisibilityTag::default(), VisibilityTag::None);
4045 }
4046
4047 #[test]
4048 fn visibility_tag_is_none_only_for_none_variant() {
4049 assert!(VisibilityTag::None.is_none());
4050 assert!(!VisibilityTag::Public.is_none());
4051 assert!(!VisibilityTag::Internal.is_none());
4052 assert!(!VisibilityTag::Beta.is_none());
4053 assert!(!VisibilityTag::Alpha.is_none());
4054 assert!(!VisibilityTag::ExpectedUnused.is_none());
4055 }
4056
4057 #[test]
4058 fn visibility_tag_suppresses_unused_for_api_tags() {
4059 assert!(VisibilityTag::Public.suppresses_unused());
4060 assert!(VisibilityTag::Internal.suppresses_unused());
4061 assert!(VisibilityTag::Beta.suppresses_unused());
4062 assert!(VisibilityTag::Alpha.suppresses_unused());
4063 }
4064
4065 #[test]
4066 fn visibility_tag_does_not_suppress_none_or_expected_unused() {
4067 assert!(!VisibilityTag::None.suppresses_unused());
4068 assert!(!VisibilityTag::ExpectedUnused.suppresses_unused());
4069 }
4070
4071 // --- is_public_env_path ---
4072
4073 #[test]
4074 fn is_public_env_path_process_env_public_prefix() {
4075 assert!(is_public_env_path("process.env.NEXT_PUBLIC_API_URL"));
4076 assert!(is_public_env_path("process.env.VITE_APP_KEY"));
4077 assert!(is_public_env_path("process.env.REACT_APP_TITLE"));
4078 assert!(is_public_env_path("process.env.NODE_ENV"));
4079 }
4080
4081 #[test]
4082 fn is_public_env_path_import_meta_env_public_prefix() {
4083 assert!(is_public_env_path("import.meta.env.VITE_BASE_URL"));
4084 assert!(is_public_env_path("import.meta.env.PUBLIC_API"));
4085 }
4086
4087 #[test]
4088 fn is_public_env_path_secret_env_vars_are_not_public() {
4089 assert!(!is_public_env_path("process.env.SECRET_KEY"));
4090 assert!(!is_public_env_path("process.env.DATABASE_PASSWORD"));
4091 assert!(!is_public_env_path("import.meta.env.API_TOKEN"));
4092 }
4093
4094 #[test]
4095 fn is_public_env_path_non_env_paths_are_not_public() {
4096 assert!(!is_public_env_path("req.query.id"));
4097 assert!(!is_public_env_path("process.argv"));
4098 assert!(!is_public_env_path("window.location.href"));
4099 }
4100
4101 // --- is_public_env_var edge cases ---
4102
4103 #[test]
4104 fn is_public_env_var_exact_matches() {
4105 assert!(is_public_env_var("NODE_ENV"));
4106 }
4107
4108 #[test]
4109 fn is_public_env_var_all_known_prefixes() {
4110 assert!(is_public_env_var("NUXT_PUBLIC_API_URL"));
4111 assert!(is_public_env_var("PUBLIC_API_KEY"));
4112 assert!(is_public_env_var("GATSBY_APP_ID"));
4113 assert!(is_public_env_var("EXPO_PUBLIC_SENTRY_DSN"));
4114 assert!(is_public_env_var("STORYBOOK_ENV"));
4115 }
4116
4117 #[test]
4118 fn is_public_env_var_secret_token_beats_metadata_token() {
4119 // "SECRET_SHA": has SECRET (wins) and SHA (metadata); should NOT be public
4120 assert!(!is_public_env_var("SECRET_SHA"));
4121 // "REF_TOKEN": has TOKEN (secret) and REF (metadata); should NOT be public
4122 assert!(!is_public_env_var("REF_TOKEN"));
4123 }
4124
4125 #[test]
4126 fn is_public_env_var_plain_unknown_names_are_not_public() {
4127 assert!(!is_public_env_var("MY_SERVICE_URL"));
4128 assert!(!is_public_env_var("FEATURE_FLAG"));
4129 assert!(!is_public_env_var("DATABASE_URL"));
4130 }
4131
4132 // --- SinkSite::span ---
4133
4134 #[test]
4135 fn sink_site_span_reconstructs_from_offsets() {
4136 let site = SinkSite {
4137 sink_shape: SinkShape::Call,
4138 callee_path: "eval".to_string(),
4139 arg_index: 0,
4140 arg_is_non_literal: true,
4141 arg_kind: SinkArgKind::Other,
4142 arg_literal: None,
4143 regex_pattern: None,
4144 object_properties: Vec::new(),
4145 object_property_keys: Vec::new(),
4146 object_property_keys_complete: false,
4147 arg_idents: Vec::new(),
4148 arg_source_paths: Vec::new(),
4149 span_start: 5,
4150 span_end: 15,
4151 url_arg_literal: None,
4152 url_shape: None,
4153 };
4154 let s = site.span();
4155 assert_eq!(s.start, 5);
4156 assert_eq!(s.end, 15);
4157 }
4158
4159 // --- SecurityControlKind ---
4160
4161 #[test]
4162 fn security_control_kind_equality_and_ordering() {
4163 assert_eq!(
4164 SecurityControlKind::Sanitization,
4165 SecurityControlKind::Sanitization
4166 );
4167 assert_eq!(
4168 SecurityControlKind::Validation,
4169 SecurityControlKind::Validation
4170 );
4171 assert_ne!(
4172 SecurityControlKind::Sanitization,
4173 SecurityControlKind::Validation
4174 );
4175 assert!(SecurityControlKind::Sanitization < SecurityControlKind::Validation);
4176 assert!(SecurityControlKind::Authentication < SecurityControlKind::Authorization);
4177 }
4178
4179 // --- SanitizerScope ---
4180
4181 #[test]
4182 fn sanitizer_scope_equality_and_ordering() {
4183 assert_eq!(SanitizerScope::Html, SanitizerScope::Html);
4184 assert_eq!(SanitizerScope::Url, SanitizerScope::Url);
4185 assert_eq!(SanitizerScope::Path, SanitizerScope::Path);
4186 assert_eq!(SanitizerScope::SqlIdentifier, SanitizerScope::SqlIdentifier);
4187 assert_ne!(SanitizerScope::Html, SanitizerScope::Url);
4188 assert!(SanitizerScope::Html < SanitizerScope::Url);
4189 }
4190
4191 // --- SkippedSecurityCalleeReason ---
4192
4193 #[test]
4194 fn skipped_security_callee_reason_equality() {
4195 assert_eq!(
4196 SkippedSecurityCalleeReason::ComputedMember,
4197 SkippedSecurityCalleeReason::ComputedMember
4198 );
4199 assert_ne!(
4200 SkippedSecurityCalleeReason::ComputedMember,
4201 SkippedSecurityCalleeReason::DynamicDispatch
4202 );
4203 assert_ne!(
4204 SkippedSecurityCalleeReason::DynamicDispatch,
4205 SkippedSecurityCalleeReason::UnsupportedAssignmentObject
4206 );
4207 }
4208
4209 // --- SkippedSecurityCalleeExpressionKind ---
4210
4211 #[test]
4212 fn skipped_security_callee_expression_kind_equality() {
4213 use SkippedSecurityCalleeExpressionKind as K;
4214 assert_eq!(K::StaticMemberExpression, K::StaticMemberExpression);
4215 assert_eq!(K::ComputedMemberExpression, K::ComputedMemberExpression);
4216 assert_eq!(K::Identifier, K::Identifier);
4217 assert_eq!(K::Other, K::Other);
4218 assert_ne!(K::StaticMemberExpression, K::ComputedMemberExpression);
4219 assert_ne!(K::Identifier, K::Other);
4220 }
4221
4222 // --- SinkLiteralValue ---
4223
4224 #[test]
4225 fn sink_literal_value_equality() {
4226 assert_eq!(
4227 SinkLiteralValue::String("x".to_string()),
4228 SinkLiteralValue::String("x".to_string())
4229 );
4230 assert_ne!(
4231 SinkLiteralValue::String("x".to_string()),
4232 SinkLiteralValue::String("y".to_string())
4233 );
4234 assert_eq!(SinkLiteralValue::Integer(42), SinkLiteralValue::Integer(42));
4235 assert_ne!(SinkLiteralValue::Integer(1), SinkLiteralValue::Integer(2));
4236 assert_eq!(
4237 SinkLiteralValue::Boolean(true),
4238 SinkLiteralValue::Boolean(true)
4239 );
4240 assert_ne!(
4241 SinkLiteralValue::Boolean(true),
4242 SinkLiteralValue::Boolean(false)
4243 );
4244 assert_eq!(SinkLiteralValue::Null, SinkLiteralValue::Null);
4245 assert_ne!(SinkLiteralValue::Null, SinkLiteralValue::Boolean(false));
4246 }
4247
4248 // --- SecurityUrlShape ---
4249
4250 #[test]
4251 fn security_url_shape_equality() {
4252 assert_eq!(
4253 SecurityUrlShape::FixedOriginDynamicPath,
4254 SecurityUrlShape::FixedOriginDynamicPath
4255 );
4256 assert_eq!(
4257 SecurityUrlShape::DynamicOrigin,
4258 SecurityUrlShape::DynamicOrigin
4259 );
4260 assert_ne!(
4261 SecurityUrlShape::FixedOriginDynamicPath,
4262 SecurityUrlShape::DynamicOrigin
4263 );
4264 }
4265
4266 // --- FlagUseKind ---
4267
4268 #[test]
4269 fn flag_use_kind_equality() {
4270 assert_eq!(FlagUseKind::EnvVar, FlagUseKind::EnvVar);
4271 assert_eq!(FlagUseKind::SdkCall, FlagUseKind::SdkCall);
4272 assert_eq!(FlagUseKind::ConfigObject, FlagUseKind::ConfigObject);
4273 assert_ne!(FlagUseKind::EnvVar, FlagUseKind::SdkCall);
4274 assert_ne!(FlagUseKind::SdkCall, FlagUseKind::ConfigObject);
4275 }
4276
4277 // --- ComplexityMetric ---
4278
4279 #[test]
4280 fn complexity_metric_equality() {
4281 assert_eq!(ComplexityMetric::Cyclomatic, ComplexityMetric::Cyclomatic);
4282 assert_eq!(ComplexityMetric::Cognitive, ComplexityMetric::Cognitive);
4283 assert_ne!(ComplexityMetric::Cyclomatic, ComplexityMetric::Cognitive);
4284 }
4285
4286 // --- ComplexityContributionKind ---
4287
4288 #[test]
4289 fn complexity_contribution_kind_equality_spot_check() {
4290 use ComplexityContributionKind as K;
4291 assert_eq!(K::If, K::If);
4292 assert_eq!(K::Else, K::Else);
4293 assert_eq!(K::ElseIf, K::ElseIf);
4294 assert_eq!(K::Ternary, K::Ternary);
4295 assert_eq!(K::LogicalAnd, K::LogicalAnd);
4296 assert_eq!(K::LogicalOr, K::LogicalOr);
4297 assert_eq!(K::NullishCoalescing, K::NullishCoalescing);
4298 assert_eq!(K::LogicalAssignment, K::LogicalAssignment);
4299 assert_eq!(K::OptionalChain, K::OptionalChain);
4300 assert_eq!(K::For, K::For);
4301 assert_eq!(K::ForIn, K::ForIn);
4302 assert_eq!(K::ForOf, K::ForOf);
4303 assert_eq!(K::While, K::While);
4304 assert_eq!(K::DoWhile, K::DoWhile);
4305 assert_eq!(K::Switch, K::Switch);
4306 assert_eq!(K::Case, K::Case);
4307 assert_eq!(K::Catch, K::Catch);
4308 assert_eq!(K::LabeledBreak, K::LabeledBreak);
4309 assert_eq!(K::LabeledContinue, K::LabeledContinue);
4310 assert_eq!(K::JsxDepth, K::JsxDepth);
4311 assert_eq!(K::HookDensity, K::HookDensity);
4312 assert_eq!(K::PropCount, K::PropCount);
4313 assert_eq!(K::Await, K::Await);
4314 assert_eq!(K::Then, K::Then);
4315 assert_ne!(K::If, K::Else);
4316 assert_ne!(K::For, K::While);
4317 assert_ne!(K::Switch, K::Case);
4318 }
4319
4320 // --- MisplacedDirectiveSite ---
4321
4322 #[test]
4323 fn misplaced_directive_site_equality() {
4324 let client = MisplacedDirectiveSite {
4325 is_server: false,
4326 span_start: 10,
4327 };
4328 let server = MisplacedDirectiveSite {
4329 is_server: true,
4330 span_start: 10,
4331 };
4332 let client2 = MisplacedDirectiveSite {
4333 is_server: false,
4334 span_start: 10,
4335 };
4336 assert_eq!(client, client2);
4337 assert_ne!(client, server);
4338 }
4339
4340 #[test]
4341 fn misplaced_directive_site_is_server_flag() {
4342 let site = MisplacedDirectiveSite {
4343 is_server: true,
4344 span_start: 42,
4345 };
4346 assert!(site.is_server);
4347 assert_eq!(site.span_start, 42);
4348
4349 let client_site = MisplacedDirectiveSite {
4350 is_server: false,
4351 span_start: 0,
4352 };
4353 assert!(!client_site.is_server);
4354 }
4355
4356 // --- DiRole / DiFramework ---
4357
4358 #[test]
4359 fn di_role_equality() {
4360 assert_eq!(DiRole::Provide, DiRole::Provide);
4361 assert_eq!(DiRole::Inject, DiRole::Inject);
4362 assert_ne!(DiRole::Provide, DiRole::Inject);
4363 }
4364
4365 #[test]
4366 fn di_framework_equality() {
4367 assert_eq!(DiFramework::Vue, DiFramework::Vue);
4368 assert_eq!(DiFramework::Svelte, DiFramework::Svelte);
4369 assert_eq!(DiFramework::Angular, DiFramework::Angular);
4370 assert_ne!(DiFramework::Vue, DiFramework::Svelte);
4371 assert_ne!(DiFramework::Svelte, DiFramework::Angular);
4372 }
4373
4374 // --- ComponentEmit ---
4375
4376 #[test]
4377 fn component_emit_equality() {
4378 let a = ComponentEmit {
4379 name: "close".to_string(),
4380 span_start: 10,
4381 used: true,
4382 };
4383 let b = ComponentEmit {
4384 name: "close".to_string(),
4385 span_start: 10,
4386 used: true,
4387 };
4388 let different_used = ComponentEmit {
4389 name: "close".to_string(),
4390 span_start: 10,
4391 used: false,
4392 };
4393 let different_name = ComponentEmit {
4394 name: "open".to_string(),
4395 span_start: 10,
4396 used: true,
4397 };
4398 assert_eq!(a, b);
4399 assert_ne!(a, different_used);
4400 assert_ne!(a, different_name);
4401 }
4402
4403 // --- DispatchedEvent ---
4404
4405 #[test]
4406 fn dispatched_event_equality() {
4407 let a = DispatchedEvent {
4408 name: "myEvent".to_string(),
4409 span_start: 20,
4410 };
4411 let b = DispatchedEvent {
4412 name: "myEvent".to_string(),
4413 span_start: 20,
4414 };
4415 let c = DispatchedEvent {
4416 name: "otherEvent".to_string(),
4417 span_start: 20,
4418 };
4419 let d = DispatchedEvent {
4420 name: "myEvent".to_string(),
4421 span_start: 99,
4422 };
4423 assert_eq!(a, b);
4424 assert_ne!(a, c);
4425 assert_ne!(a, d);
4426 }
4427
4428 // --- AngularInputMember / AngularOutputMember ---
4429
4430 #[test]
4431 fn angular_input_member_equality() {
4432 let a = AngularInputMember {
4433 name: "title".to_string(),
4434 span_start: 5,
4435 };
4436 let b = AngularInputMember {
4437 name: "title".to_string(),
4438 span_start: 5,
4439 };
4440 let c = AngularInputMember {
4441 name: "label".to_string(),
4442 span_start: 5,
4443 };
4444 assert_eq!(a, b);
4445 assert_ne!(a, c);
4446 }
4447
4448 #[test]
4449 fn angular_output_member_equality() {
4450 let a = AngularOutputMember {
4451 name: "clicked".to_string(),
4452 span_start: 8,
4453 };
4454 let b = AngularOutputMember {
4455 name: "clicked".to_string(),
4456 span_start: 8,
4457 };
4458 let c = AngularOutputMember {
4459 name: "hovered".to_string(),
4460 span_start: 8,
4461 };
4462 assert_eq!(a, b);
4463 assert_ne!(a, c);
4464 }
4465
4466 // --- AngularComponentSelector ---
4467
4468 #[test]
4469 fn angular_component_selector_fields() {
4470 let s = AngularComponentSelector {
4471 selectors: vec!["app-foo".to_string(), "[appFoo]".to_string()],
4472 span_start: 100,
4473 class_name: "FooComponent".to_string(),
4474 };
4475 assert_eq!(s.selectors.len(), 2);
4476 assert_eq!(s.selectors[0], "app-foo");
4477 assert_eq!(s.selectors[1], "[appFoo]");
4478 assert_eq!(s.class_name, "FooComponent");
4479 }
4480
4481 #[test]
4482 fn angular_component_selector_equality() {
4483 let a = AngularComponentSelector {
4484 selectors: vec!["app-bar".to_string()],
4485 span_start: 0,
4486 class_name: "BarComponent".to_string(),
4487 };
4488 let b = AngularComponentSelector {
4489 selectors: vec!["app-bar".to_string()],
4490 span_start: 0,
4491 class_name: "BarComponent".to_string(),
4492 };
4493 let c = AngularComponentSelector {
4494 selectors: vec!["app-baz".to_string()],
4495 span_start: 0,
4496 class_name: "BazComponent".to_string(),
4497 };
4498 assert_eq!(a, b);
4499 assert_ne!(a, c);
4500 }
4501
4502 // --- LoadReturnKey ---
4503
4504 #[test]
4505 fn load_return_key_equality() {
4506 let a = LoadReturnKey {
4507 name: "user".to_string(),
4508 span_start: 50,
4509 span_end: 54,
4510 };
4511 let b = LoadReturnKey {
4512 name: "user".to_string(),
4513 span_start: 50,
4514 span_end: 54,
4515 };
4516 let c = LoadReturnKey {
4517 name: "posts".to_string(),
4518 span_start: 50,
4519 span_end: 55,
4520 };
4521 assert_eq!(a, b);
4522 assert_ne!(a, c);
4523 }
4524
4525 #[test]
4526 fn load_return_key_span_fields() {
4527 let key = LoadReturnKey {
4528 name: "data".to_string(),
4529 span_start: 10,
4530 span_end: 14,
4531 };
4532 assert_eq!(key.span_start, 10);
4533 assert_eq!(key.span_end, 14);
4534 assert_eq!(key.name, "data");
4535 }
4536
4537 // --- ComponentFunctionKind ---
4538
4539 #[test]
4540 fn component_function_kind_equality() {
4541 assert_eq!(ComponentFunctionKind::FnDecl, ComponentFunctionKind::FnDecl);
4542 assert_eq!(ComponentFunctionKind::Arrow, ComponentFunctionKind::Arrow);
4543 assert_eq!(
4544 ComponentFunctionKind::ForwardRefWrapper,
4545 ComponentFunctionKind::ForwardRefWrapper
4546 );
4547 assert_eq!(
4548 ComponentFunctionKind::MemoWrapper,
4549 ComponentFunctionKind::MemoWrapper
4550 );
4551 assert_ne!(ComponentFunctionKind::FnDecl, ComponentFunctionKind::Arrow);
4552 assert_ne!(
4553 ComponentFunctionKind::ForwardRefWrapper,
4554 ComponentFunctionKind::MemoWrapper
4555 );
4556 }
4557
4558 // --- HookUseKind ---
4559
4560 #[test]
4561 fn hook_use_kind_equality() {
4562 assert_eq!(HookUseKind::UseState, HookUseKind::UseState);
4563 assert_eq!(HookUseKind::UseEffect, HookUseKind::UseEffect);
4564 assert_eq!(HookUseKind::UseMemo, HookUseKind::UseMemo);
4565 assert_eq!(HookUseKind::UseCallback, HookUseKind::UseCallback);
4566 assert_eq!(HookUseKind::Custom, HookUseKind::Custom);
4567 assert_ne!(HookUseKind::UseState, HookUseKind::UseEffect);
4568 assert_ne!(HookUseKind::UseMemo, HookUseKind::Custom);
4569 }
4570
4571 // --- HookUse ---
4572
4573 #[test]
4574 fn hook_use_fields() {
4575 let h = HookUse {
4576 kind: HookUseKind::UseEffect,
4577 dep_array_arity: Some(2),
4578 span_start: 30,
4579 component: "Widget".to_string(),
4580 };
4581 assert_eq!(h.kind, HookUseKind::UseEffect);
4582 assert_eq!(h.dep_array_arity, Some(2));
4583 assert_eq!(h.span_start, 30);
4584 assert_eq!(h.component, "Widget");
4585 }
4586
4587 #[test]
4588 fn hook_use_no_dep_array() {
4589 let h = HookUse {
4590 kind: HookUseKind::UseCallback,
4591 dep_array_arity: None,
4592 span_start: 0,
4593 component: String::new(),
4594 };
4595 assert!(h.dep_array_arity.is_none());
4596 }
4597
4598 // --- MemberKind::StoreMember (missed in existing bitcode test) ---
4599
4600 #[test]
4601 fn member_kind_store_member_bitcode_roundtrip() {
4602 let kind = MemberKind::StoreMember;
4603 let bytes = bitcode::encode(&kind);
4604 let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
4605 assert_eq!(decoded, kind);
4606 }
4607
4608 // --- RenderEdge / ForwardAttr ---
4609
4610 #[test]
4611 fn render_edge_fields() {
4612 let edge = RenderEdge {
4613 parent_component: "Parent".to_string(),
4614 child_component_name: "Child".to_string(),
4615 attr_names: vec!["title".to_string(), "onClick".to_string()],
4616 has_spread: false,
4617 forward_attrs: vec![ForwardAttr {
4618 attr: "title".to_string(),
4619 root: "props".to_string(),
4620 }],
4621 has_complex_forward: false,
4622 };
4623 assert_eq!(edge.parent_component, "Parent");
4624 assert_eq!(edge.child_component_name, "Child");
4625 assert_eq!(edge.attr_names.len(), 2);
4626 assert!(!edge.has_spread);
4627 assert_eq!(edge.forward_attrs.len(), 1);
4628 assert_eq!(edge.forward_attrs[0].attr, "title");
4629 assert_eq!(edge.forward_attrs[0].root, "props");
4630 assert!(!edge.has_complex_forward);
4631 }
4632
4633 #[test]
4634 fn render_edge_with_spread() {
4635 let edge = RenderEdge {
4636 parent_component: "Wrapper".to_string(),
4637 child_component_name: "Inner".to_string(),
4638 attr_names: Vec::new(),
4639 has_spread: true,
4640 forward_attrs: Vec::new(),
4641 has_complex_forward: true,
4642 };
4643 assert!(edge.has_spread);
4644 assert!(edge.has_complex_forward);
4645 }
4646
4647 // --- ComponentFunction ---
4648
4649 #[test]
4650 fn component_function_fields() {
4651 let cf = ComponentFunction {
4652 name: "MyButton".to_string(),
4653 span_start: 0,
4654 kind: ComponentFunctionKind::Arrow,
4655 is_exported: true,
4656 has_unharvestable_props: false,
4657 uses_clone_element: false,
4658 renders_provider: false,
4659 has_children_as_function: false,
4660 is_pure_passthrough: false,
4661 };
4662 assert_eq!(cf.name, "MyButton");
4663 assert_eq!(cf.kind, ComponentFunctionKind::Arrow);
4664 assert!(cf.is_exported);
4665 assert!(!cf.has_unharvestable_props);
4666 assert!(!cf.is_pure_passthrough);
4667 }
4668
4669 #[test]
4670 fn component_function_passthrough_flag() {
4671 let cf = ComponentFunction {
4672 name: "Passthrough".to_string(),
4673 span_start: 5,
4674 kind: ComponentFunctionKind::FnDecl,
4675 is_exported: false,
4676 has_unharvestable_props: false,
4677 uses_clone_element: false,
4678 renders_provider: false,
4679 has_children_as_function: false,
4680 is_pure_passthrough: true,
4681 };
4682 assert!(cf.is_pure_passthrough);
4683 assert!(!cf.is_exported);
4684 }
4685
4686 // --- DiKeySite ---
4687
4688 #[test]
4689 fn di_key_site_fields() {
4690 let site = DiKeySite {
4691 key_local: "MY_KEY".to_string(),
4692 role: DiRole::Provide,
4693 framework: DiFramework::Vue,
4694 span_start: 77,
4695 };
4696 assert_eq!(site.key_local, "MY_KEY");
4697 assert_eq!(site.role, DiRole::Provide);
4698 assert_eq!(site.framework, DiFramework::Vue);
4699 assert_eq!(site.span_start, 77);
4700 }
4701
4702 #[test]
4703 fn di_key_site_inject_svelte() {
4704 let site = DiKeySite {
4705 key_local: "ctx_key".to_string(),
4706 role: DiRole::Inject,
4707 framework: DiFramework::Svelte,
4708 span_start: 0,
4709 };
4710 assert_eq!(site.role, DiRole::Inject);
4711 assert_eq!(site.framework, DiFramework::Svelte);
4712 }
4713
4714 // --- release_resolution_payload: page data store whole-use derivation ---
4715
4716 #[test]
4717 fn release_payload_derives_page_data_store_whole_use_from_page_data() {
4718 let mut m = minimal_module_info();
4719 m.whole_object_uses = vec!["page.data".to_string()].into();
4720 m.release_resolution_payload();
4721 assert!(m.has_page_data_store_whole_use);
4722 }
4723
4724 #[test]
4725 fn release_payload_derives_page_data_store_whole_use_from_dollar_page_data() {
4726 let mut m = minimal_module_info();
4727 m.whole_object_uses = vec!["$page.data".to_string()].into();
4728 m.release_resolution_payload();
4729 assert!(m.has_page_data_store_whole_use);
4730 }
4731
4732 #[test]
4733 fn release_payload_does_not_set_page_data_store_whole_use_for_other_names() {
4734 let mut m = minimal_module_info();
4735 m.whole_object_uses = vec!["data".to_string(), "page".to_string()].into();
4736 m.release_resolution_payload();
4737 assert!(!m.has_page_data_store_whole_use);
4738 }
4739
4740 #[test]
4741 fn release_payload_derives_route_loader_data_whole_use() {
4742 let mut m = minimal_module_info();
4743 m.whole_object_uses = vec!["$fallow.routeLoaderData".to_string()].into();
4744 m.release_resolution_payload();
4745 assert!(m.has_route_loader_data_whole_use);
4746 }
4747
4748 // --- release_resolution_payload: referenced_import_bindings derivation ---
4749
4750 #[test]
4751 fn release_payload_referenced_bindings_excludes_empty_local_names() {
4752 let mut m = minimal_module_info();
4753 m.imports = vec![
4754 ImportInfo {
4755 source: "./styles.css".to_string(),
4756 imported_name: ImportedName::SideEffect,
4757 local_name: String::new(), // empty = side-effect import
4758 is_type_only: false,
4759 is_type_only_star: false,
4760 from_style: true,
4761 span: span(),
4762 source_span: span(),
4763 },
4764 ImportInfo {
4765 source: "react".to_string(),
4766 imported_name: ImportedName::Default,
4767 local_name: "React".to_string(),
4768 is_type_only: false,
4769 is_type_only_star: false,
4770 from_style: false,
4771 span: span(),
4772 source_span: span(),
4773 },
4774 ];
4775 m.unused_import_bindings = vec!["React".to_string()];
4776 m.release_resolution_payload();
4777 // "React" was unused, empty local is filtered; result should be empty
4778 assert!(m.referenced_import_bindings.is_empty());
4779 }
4780
4781 #[test]
4782 fn release_payload_referenced_bindings_sorted_and_deduped() {
4783 let mut m = minimal_module_info();
4784 // Two imports with the same local name (unusual but possible via re-exports)
4785 m.imports = vec![
4786 ImportInfo {
4787 source: "a".to_string(),
4788 imported_name: ImportedName::Named("foo".to_string()),
4789 local_name: "foo".to_string(),
4790 is_type_only: false,
4791 is_type_only_star: false,
4792 from_style: false,
4793 span: span(),
4794 source_span: span(),
4795 },
4796 ImportInfo {
4797 source: "b".to_string(),
4798 imported_name: ImportedName::Named("bar".to_string()),
4799 local_name: "bar".to_string(),
4800 is_type_only: false,
4801 is_type_only_star: false,
4802 from_style: false,
4803 span: span(),
4804 source_span: span(),
4805 },
4806 ImportInfo {
4807 source: "c".to_string(),
4808 imported_name: ImportedName::Named("foo".to_string()),
4809 local_name: "foo".to_string(),
4810 is_type_only: false,
4811 is_type_only_star: false,
4812 from_style: false,
4813 span: span(),
4814 source_span: span(),
4815 },
4816 ];
4817 m.unused_import_bindings = Vec::new();
4818 m.release_resolution_payload();
4819 // sorted: ["bar", "foo"] with "foo" deduped
4820 assert_eq!(
4821 m.referenced_import_bindings,
4822 vec!["bar".to_string(), "foo".to_string()]
4823 );
4824 }
4825
4826 // --- CalleeUse ---
4827
4828 #[test]
4829 fn callee_use_fields() {
4830 let cu = CalleeUse {
4831 callee_path: "child_process.exec".to_string(),
4832 span_start: 100,
4833 };
4834 assert_eq!(cu.callee_path, "child_process.exec");
4835 assert_eq!(cu.span_start, 100);
4836 }
4837
4838 // --- Helper to build a minimal ModuleInfo for targeted tests ---
4839
4840 fn minimal_module_info() -> ModuleInfo {
4841 ModuleInfo::empty(FileId(0))
4842 }
4843
4844 fn push_semantic_fact(module: &mut ModuleInfo, fact: SemanticFact) {
4845 let mut facts = std::mem::take(&mut module.semantic_facts).to_vec();
4846 facts.push(fact);
4847 module.semantic_facts = facts.into();
4848 }
4849
4850 #[test]
4851 fn dynamic_custom_element_render_helper_prefers_typed_fact() {
4852 let mut module = minimal_module_info();
4853 push_semantic_fact(
4854 &mut module,
4855 SemanticFact::DynamicCustomElementRender(DynamicCustomElementRenderFact),
4856 );
4857
4858 assert!(has_dynamic_custom_element_render(&module));
4859 }
4860
4861 #[test]
4862 fn function_complexity_bitcode_roundtrip() {
4863 let fc = FunctionComplexity {
4864 name: "processData".to_string(),
4865 is_private_member: true,
4866 line: 42,
4867 col: 4,
4868 cyclomatic: 15,
4869 cognitive: 25,
4870 line_count: 80,
4871 param_count: 3,
4872 react_hook_count: 0,
4873 react_jsx_max_depth: 0,
4874 react_prop_count: 0,
4875 source_hash: Some("0123456789abcdef".to_string()),
4876 contributions: vec![
4877 ComplexityContribution {
4878 line: 43,
4879 col: 8,
4880 metric: ComplexityMetric::Cyclomatic,
4881 kind: ComplexityContributionKind::If,
4882 weight: 1,
4883 nesting: 0,
4884 },
4885 ComplexityContribution {
4886 line: 45,
4887 col: 12,
4888 metric: ComplexityMetric::Cognitive,
4889 kind: ComplexityContributionKind::ElseIf,
4890 weight: 3,
4891 nesting: 2,
4892 },
4893 ],
4894 };
4895 let bytes = bitcode::encode(&fc);
4896 let decoded: FunctionComplexity = bitcode::decode(&bytes).unwrap();
4897 assert_eq!(decoded.name, "processData");
4898 assert!(decoded.is_private_member);
4899 assert_eq!(decoded.line, 42);
4900 assert_eq!(decoded.col, 4);
4901 assert_eq!(decoded.cyclomatic, 15);
4902 assert_eq!(decoded.cognitive, 25);
4903 assert_eq!(decoded.line_count, 80);
4904 assert_eq!(decoded.source_hash.as_deref(), Some("0123456789abcdef"));
4905 assert_eq!(decoded.contributions.len(), 2);
4906 assert_eq!(
4907 decoded.contributions[1].kind,
4908 ComplexityContributionKind::ElseIf
4909 );
4910 assert_eq!(decoded.contributions[1].weight, 3);
4911 assert_eq!(decoded.contributions[1].nesting, 2);
4912 assert_eq!(decoded.contributions[1].metric, ComplexityMetric::Cognitive);
4913 }
4914}