Skip to main content

fallow_types/
extract.rs

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