Skip to main content

fallow_types/
extract.rs

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