Skip to main content

fallow_types/
extract.rs

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