Skip to main content

fallow_types/
extract.rs

1//! Module extraction types.
2
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use oxc_span::Span;
7
8pub use crate::complexity_contribution::{
9    ComplexityContribution, ComplexityContributionKind, ComplexityMetric,
10};
11use crate::discover::FileId;
12use crate::{inline_threshold::InlineThresholdOverrides, suppress::Suppression};
13#[path = "extract_playwright_facts.rs"]
14mod playwright_facts;
15use playwright_facts::{
16    playwright_fixture_alias_facts, playwright_fixture_definition_facts,
17    playwright_fixture_type_facts, playwright_fixture_use_facts,
18};
19
20/// Extracted module information from a single file.
21///
22/// The `Arc<[T]>` fields are immutable after extraction and are shared by
23/// refcount with the resolver's per-file output, so the resolve/graph path
24/// does not deep-copy per-file extraction payloads.
25#[derive(Debug, Clone)]
26pub struct ModuleInfo {
27    /// Unique identifier for this file.
28    pub file_id: FileId,
29    /// All export declarations in this module.
30    pub exports: Arc<[ExportInfo]>,
31    /// All import declarations in this module.
32    pub imports: Vec<ImportInfo>,
33    /// All re-export declarations (e.g., `export { foo } from './bar'`).
34    pub re_exports: Vec<ReExportInfo>,
35    /// All dynamic `import()` calls with string literal sources.
36    pub dynamic_imports: Vec<DynamicImportInfo>,
37    /// Dynamic import patterns.
38    pub dynamic_import_patterns: Vec<DynamicImportPattern>,
39    /// All `require()` calls.
40    pub require_calls: Vec<RequireCallInfo>,
41    /// Package names statically referenced through package path resolution.
42    pub package_path_references: Box<[String]>,
43    /// Package names that a module augmentation (`declare module 'pkg'` in a
44    /// module file) names. They credit the package as a type-only use.
45    pub type_package_references: Box<[String]>,
46    /// Binary names found in `node_modules/.bin/<name>` paths in string
47    /// literals and template quasis. The analysis maps each name to the
48    /// package that declares the binary.
49    pub bin_path_references: Box<[String]>,
50    /// Package names from direct `require.resolve('pkg')` calls, each with the
51    /// byte offset of its call. A name from a resolver function, a loop
52    /// binding or a static table has no site, because it is a heuristic
53    /// credit. The unlisted-dependency check reports a site like an import.
54    pub package_resolve_sites: Box<[(String, u32)]>,
55    /// Static member access expressions (e.g., `Status.Active`).
56    pub member_accesses: Arc<[MemberAccess]>,
57    /// Typed semantic facts produced by extraction for cross-layer analysis.
58    pub semantic_facts: Arc<[SemanticFact]>,
59    /// Identifiers used in whole-object access patterns.
60    pub whole_object_uses: Arc<[String]>,
61    /// Whether this module uses CommonJS exports.
62    pub has_cjs_exports: bool,
63    /// Whether this module declares an Angular component `templateUrl`.
64    pub has_angular_component_template_url: bool,
65    /// xxh3 hash of the file content for incremental caching.
66    pub content_hash: u64,
67    /// Number of parser diagnostics the parse of this file produced. Non-zero
68    /// means imports, exports and references after the first error may be
69    /// missing (`source-parse-degraded`, which never withholds a finding).
70    /// Zero for non-JS extraction paths, which do not run the oxc parser.
71    pub parse_error_count: u32,
72    /// `true` when the parser abandoned the file instead of recovering. The
73    /// extracted module is then a fragment of the real one at best.
74    pub parse_panicked: bool,
75    /// `true` when the file nests too deep to parse, so it was not parsed.
76    pub parse_nesting_too_deep: bool,
77    /// Inline suppression directives parsed from comments.
78    pub suppressions: Vec<Suppression>,
79    /// Suppression tokens that parse to no `IssueKind`, reported as stale (issue #449).
80    pub unknown_suppression_kinds: Vec<crate::suppress::UnknownSuppressionKind>,
81    /// Range suppression markers with a problem. They have no effect.
82    pub range_marker_problems: Vec<crate::suppress::RangeMarkerProblem>,
83    /// `fallow-override-threshold-next-line` comments and their problems.
84    pub inline_threshold_overrides: InlineThresholdOverrides,
85    /// Local names of import bindings that are never referenced in this file.
86    /// Populated via `oxc_semantic` scope analysis. Used at graph-build time
87    /// to skip adding references for imports whose binding is never read,
88    /// improving unused-export detection precision.
89    pub unused_import_bindings: Vec<String>,
90    /// Local import bindings that are referenced from TypeScript type positions.
91    /// Used to distinguish value-namespace and type-namespace references when a
92    /// module exports both `const X` and `type X`.
93    pub type_referenced_import_bindings: Vec<String>,
94    /// Local import bindings referenced from runtime/value positions.
95    pub value_referenced_import_bindings: Vec<String>,
96    /// Pre-computed byte offsets where each line starts.
97    pub line_offsets: Vec<u32>,
98    /// Per-function complexity metrics.
99    pub complexity: Vec<FunctionComplexity>,
100    /// Feature flag use sites.
101    pub flag_uses: Vec<FlagUse>,
102    /// Flag-key registries this module exports, and flag reads that name a
103    /// member of an imported registry. `None` for the common module with
104    /// neither.
105    pub flag_registry_facts: Option<Box<FlagRegistryFacts>>,
106    /// Heritage metadata for exported classes that declare `implements`.
107    pub class_heritage: Vec<ClassHeritageInfo>,
108    /// Exported free-function factories that provably return one class instance
109    /// (`export function useApi() { return new RESTApi() }`). Origin-module proof
110    /// that an exported function returns a class instance, so a cross-module
111    /// `const x = useApi(); x.member` consumer can credit the returned class.
112    /// See issue #1441 (Part A).
113    pub exported_factory_returns: Arc<[FactoryReturnExport]>,
114    /// Exported factories that return an OBJECT LITERAL whose property values are
115    /// class instances (`export function createUi() { return { orders: factory.ordersPage } }`).
116    /// Each entry maps a dotted property path (`orders`, `invoke.dashboard`) to the
117    /// returned class's local name within the factory module, so a cross-module
118    /// `const ui = createUi(); ui.orders.member` consumer can credit the class. Names
119    /// are local to this module; resolution is deferred to analyze time. See issue #1858.
120    pub exported_factory_return_object_shapes: Arc<[FactoryReturnObjectShapeExport]>,
121    /// Named-type property types declared by this module's top-level interfaces
122    /// and type-literal aliases (`interface Opts { c: OptDep }`). Names are
123    /// local to this module; resolution is deferred to analyze time. Consumed
124    /// by the `unused-class-member` typed-property-hop join and the Playwright
125    /// fixture-type resolution. See issue #1785.
126    pub type_member_types: Arc<[TypeMemberTypeEntry]>,
127    /// Angular `InjectionToken<Interface>` declarations, as
128    /// `(token_export_name, interface_name)` pairs. Recorded only for
129    /// `new InjectionToken<I>(...)` initializers whose `InjectionToken` is
130    /// imported from `@angular/core`. The analyze layer follows the token's
131    /// interface type argument to the classes that `implement` it so a template
132    /// member call through `inject(TOKEN)` credits the concrete implementation.
133    /// See issue #920 (follow-up to #911 / #913).
134    pub injection_tokens: Vec<(String, String)>,
135    /// Local type-capable declarations.
136    pub local_type_declarations: Vec<LocalTypeDeclaration>,
137    /// Type references in exported public signatures.
138    pub public_signature_type_references: Vec<PublicSignatureTypeReference>,
139    /// Aliases of namespace imports re-exported through an object literal.
140    pub namespace_object_aliases: Vec<NamespaceObjectAlias>,
141    /// Deduped Iconify collection prefixes found in static icon props.
142    pub iconify_prefixes: Vec<String>,
143    /// Deduped Nuxt UI `i-<collection>-<icon>` icon class suffixes found in
144    /// static script-side icon properties.
145    pub iconify_icon_names: Vec<String>,
146    /// Bare identifiers that may be resolved by framework auto-imports.
147    pub auto_import_candidates: Vec<String>,
148    /// File-level string directives in source order (e.g. `"use client"`,
149    /// `"use server"`, `"use strict"`). Captured from `Program::directives`.
150    /// Consumed by the security `client-server-leak` detector to identify
151    /// React Server Component client boundaries.
152    pub directives: Vec<String>,
153    /// Byte-offset starts of dynamic `import()` expressions wrapped in
154    /// `next/dynamic(() => import('./X'), { ssr: false })`. The ssr:false option
155    /// is Next.js's sanctioned way to pull a client-only module, so a server-only
156    /// module reached ONLY through such an import is NOT a client-server leak. The
157    /// security `client-server-leak` BFS resolves each dynamic import to a graph
158    /// edge; these span starts let the BFS exclude exactly those edges (matched
159    /// against the edge's `import_span`). Empty for files with no ssr:false
160    /// dynamic import. Captured only by JS/TS extraction.
161    pub client_only_dynamic_import_spans: Vec<u32>,
162    /// The non-public env reads in source order, for the `client-server-leak` rule.
163    pub env_reads: Vec<EnvRead>,
164    /// Captured security sink sites (category-blind). Consumed by the
165    /// catalogue-driven `tainted_sink` detector. Captured only by JS/TS
166    /// extraction; empty for CSS/MDX/etc. See `security_matchers.toml`.
167    pub security_sinks: Vec<SinkSite>,
168    /// Count of sink-shaped nodes whose callee could not be flattened to a
169    /// static path (dynamic dispatch, computed members, aliased bindings).
170    /// Surfaced in-band so an empty catalogue result with a non-zero count is
171    /// not a clean bill.
172    pub security_sinks_skipped: u32,
173    /// Compact span-level diagnostics for skipped security sink callees. Kept
174    /// next to `security_sinks_skipped` so warm-cache and cold-cache security
175    /// output can explain where the blind spots are concentrated without source
176    /// snippets.
177    pub security_unresolved_callee_sites: Vec<SkippedSecurityCalleeSite>,
178    /// Export names (`default` for a default export) of the module-scope
179    /// functions whose body is shallow-safe: it calls only shallow `Object`
180    /// builtins and writes only one level deep into a fresh local object. The
181    /// security analysis follows a direct import of such a function one hop
182    /// and does not report its call as a name-only library sink.
183    pub inert_function_exports: Vec<String>,
184    /// Local bindings whose initializer (or destructured object) is a flattened
185    /// member-access path. Used by the security `tainted_sink` detector to
186    /// back-trace a sink argument to a known untrusted source: the analyze layer
187    /// matches each binding's `source_path` against the data-driven source
188    /// catalogue (`security_matchers.toml` `[[source]]` rows) and treats the
189    /// matching `local` names as source-tainted. Intra-module and name-based
190    /// (no scope analysis); a conservative association, never a taint proof.
191    pub tainted_bindings: Vec<TaintedBinding>,
192    /// Sink arguments that were recognized as sanitizer calls at extraction
193    /// time. Used for direct sink calls such as
194    /// `el.innerHTML = DOMPurify.sanitize(input)`.
195    pub sanitized_sink_args: Vec<SanitizedSinkArg>,
196    /// Control patterns observed in this module. Surface context only: their
197    /// presence does not establish input identity, execution order, or protection.
198    pub security_control_sites: Vec<SecurityControlSite>,
199    /// Statically flattenable callee paths invoked in this module, one entry
200    /// per path and form with the start of every site. Consumed by
201    /// `boundaries.calls.forbidden`, `banned-call` and `banned-effect`.
202    /// Captured unconditionally because extraction is config-blind; each path
203    /// string is stored once, and each extra site costs 4 bytes.
204    pub callee_uses: Vec<CalleeUse>,
205    /// Literal commands that process-spawning calls run (`spawn("git")`,
206    /// `execSync("make build")`, `` $`ffmpeg -i a` ``). Read by the
207    /// `unlisted-binaries` detector.
208    pub command_invocations: Vec<CommandInvocation>,
209    /// Per-call references to actual runtime ESM import bindings.
210    pub imported_call_sites: Arc<[ImportedCallSite]>,
211    /// Value references to runtime ESM import bindings that are not admitted
212    /// call sites, plus admitted calls that initialize a top-level declarator.
213    /// Sorted by `span_start`. Read by `fallow trace --dependency`.
214    pub import_binding_references: Arc<[ImportBindingReference]>,
215    /// `"use client"` / `"use server"` directive strings written as expression
216    /// statements in `program.body` (misplaced, NOT in the leading
217    /// prologue), so the RSC bundler silently ignores them. One entry per
218    /// occurrence. Consumed by the `misplaced-directive` detector. Captured
219    /// only by JS/TS extraction.
220    pub misplaced_directives: Vec<MisplacedDirectiveSite>,
221    /// Export LOCAL NAMES of exported functions / const-arrows whose body has an
222    /// inline `"use server"` directive (`export async function f() { "use server"
223    /// }`), captured in a NON-`"use server"` file. Consumed by the
224    /// `unused-server-action` detector to reclassify an unused inline Server
225    /// Action export out of `unused-export`. Captured only by JS/TS extraction.
226    pub inline_server_action_exports: Vec<String>,
227    /// Vue `provide`/`inject` and Svelte `setContext`/`getContext` call sites
228    /// keyed by an identifier symbol. Consumed by the `unprovided-inject`
229    /// detector to find an inject/getContext whose key is provided nowhere
230    /// project-wide. Only identifier-keyed sites are recorded (string-literal
231    /// and computed keys abstain). Captured by JS/TS and SFC extraction.
232    pub di_key_sites: Vec<DiKeySite>,
233    /// `true` when this module contains a `provide(...)` / `*.provide(...)` /
234    /// `setContext(...)` call whose key argument is NOT a plain identifier
235    /// (spread, computed, member, loop variable). Such a call can provide an
236    /// unknowable key, so the `unprovided-inject` detector abstains on ALL
237    /// inject findings project-wide when any reachable module sets this flag.
238    /// Mirrors the spread-return whole-object abstain used for Pinia stores.
239    pub has_dynamic_provide: bool,
240    /// `true` when the prologue holds `"use server"` and every value export
241    /// is an async function (a Server Action). A `"use client"` import of
242    /// such a module becomes an action reference, so the security
243    /// `client-server-leak` BFS stops at the module. `false` for every other
244    /// module, including a `"use server"` file with a non-action value
245    /// export. Captured only by JS/TS extraction.
246    pub is_server_action_module: bool,
247    /// `true` when TypeScript reads this file as adding to the global scope:
248    /// a script file (no top-level import or export), or a module file with a
249    /// top-level `declare global` block or string-named `declare module`
250    /// block. Read only for declaration files (`.d.ts`, `.d.mts`, `.d.cts`):
251    /// a declaration file without global declarations is seeded as an entry
252    /// point only when something points to it. Captured only by JS/TS
253    /// extraction; `false` for every other module.
254    pub has_global_declarations: bool,
255    /// Raw `path` values of `/// <reference path="..." />` directives in this
256    /// file, in source order. A declaration file named by one stays an entry
257    /// point. Captured only by JS/TS extraction.
258    pub triple_slash_reference_paths: Box<[String]>,
259    /// `true` when the file has a JSX element or fragment and no
260    /// `@jsxImportSource` or `@jsxRuntime classic` pragma. A bundler or test
261    /// config can then select the automatic JSX runtime for the file, so the
262    /// resolver adds the runtime edge from a plugin rule. Captured only by
263    /// JS/TS extraction; `false` for every other module.
264    pub jsx_runtime_from_config: bool,
265    /// Local names of import bindings that ARE referenced somewhere in this file
266    /// (script value/type position OR template/markup). The complement of
267    /// `unused_import_bindings` among `imports`. Derived by
268    /// `prepare_analysis_facts` while both source vectors are still present, so
269    /// it remains readable after the owned release path clears them. It is never
270    /// cached and is recomputed on every cache load. Consumed by the
271    /// `unrendered-component` detector to credit a
272    /// Vue/Svelte SFC that some file actually imports-and-uses, distinguishing it
273    /// from a component reachable only through a barrel re-export.
274    pub referenced_import_bindings: Vec<String>,
275    /// Vue `<script setup>` `defineProps` and Svelte 5 `$props()` declared
276    /// props. Consumed by the `unused-component-prop` detector to flag a prop
277    /// referenced nowhere in its own SFC. Each entry carries `used_in_script` /
278    /// `used_in_template`.
279    pub component_props: Vec<ComponentProp>,
280    /// Cached framework-neutral component input contracts and inspected callers.
281    pub component_contracts: Option<Box<ComponentContractFacts>>,
282    /// Effect layer, tagged error and `catchTag` facts. Set only for a module
283    /// that imports `effect` or an `@effect/*` package.
284    pub effect_facts: Option<Box<EffectFacts>>,
285    /// Parameter contracts of module-scope functions, direct calls of
286    /// admitted callees and escapes of local functions. `None` when the
287    /// module has none of these facts.
288    pub function_contracts: Option<Box<FunctionContractFacts>>,
289    /// `true` when the template spreads the whole props/attrs object
290    /// (`v-bind="$attrs"` / `v-bind="$props"` / `v-bind="props"`) or the props
291    /// return is destructured with a rest element. Either form can consume a prop
292    /// indirectly, so the detector abstains on the whole file.
293    pub has_props_attrs_fallthrough: bool,
294    /// `true` when the SFC calls `defineExpose(...)`. A prop may be re-exposed,
295    /// so the detector conservatively abstains on the whole file.
296    pub has_define_expose: bool,
297    /// `true` when the SFC calls `defineModel(...)`. Two-way model props are out
298    /// of scope for v1, so the detector abstains on the whole file.
299    pub has_define_model: bool,
300    /// `true` when props were declared through an unharvestable shape, such as a
301    /// Vue type-reference argument or an opaque Svelte `$props()` destructure.
302    /// The detector abstains on the whole file so a prop is never falsely
303    /// flagged.
304    pub has_unharvestable_props: bool,
305    /// Vue `<script setup>` `defineEmits` declared events. Consumed by the
306    /// `unused-component-emit` detector to flag an event emitted nowhere in its
307    /// own SFC. Each entry carries `used`.
308    pub component_emits: Vec<ComponentEmit>,
309    /// Angular component/directive inputs declared via `@Input()` decorators or
310    /// signal `input()` / `input.required()` / `model()` initializers. Consumed
311    /// by the `unused-component-input` detector to flag an input read nowhere in
312    /// its own component. Empty for every non-Angular class.
313    pub angular_inputs: Vec<AngularInputMember>,
314    /// Angular component/directive outputs declared via `@Output()` decorators or
315    /// signal `output()` / `outputFromObservable()` initializers. Consumed by the
316    /// `unused-component-output` detector to flag an output emitted nowhere in its
317    /// own component. A `model()` is recorded as an input only (see
318    /// `AngularOutputMember`). Empty for every non-Angular class.
319    pub angular_outputs: Vec<AngularOutputMember>,
320    /// Angular `@Component` declarations with their `selector` value(s), harvested
321    /// from `@Component({ selector: '...' })` decorators. Consumed by the Angular
322    /// arm of the `unrendered-component` detector. Empty for every non-Angular
323    /// class and for `@Directive`. See `AngularComponentSelector`.
324    pub angular_component_selectors: Vec<AngularComponentSelector>,
325    /// Lit / web-component custom elements REGISTERED in this file via
326    /// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed
327    /// by the Lit arm of the `unrendered-component` detector, which flags a
328    /// registered element whose tag is rendered in NO `html` template
329    /// project-wide. Empty for non-Lit / non-web-component files. See
330    /// `RegisteredCustomElement`.
331    pub registered_custom_elements: Vec<RegisteredCustomElement>,
332    /// Custom-element tag names USED (rendered) in this file's `html` tagged
333    /// templates, e.g. `` html`<x-foo></x-foo>` `` -> `x-foo`. Only hyphenated
334    /// (custom-element) tags are recorded; native HTML tags are excluded by the
335    /// hyphen requirement. The detector unions these project-wide into the
336    /// rendered-tag set. Empty for files with no `html` templates.
337    pub used_custom_element_tags: Vec<String>,
338    /// Custom element selector tag names referenced in this file's Angular
339    /// templates (inline `@Component({ template })` and the linked external
340    /// `templateUrl` `.html` module), e.g. `<app-foo>` -> `app-foo`. Native HTML
341    /// tag names are excluded at harvest. The detector unions these project-wide
342    /// into the used-selector set. Empty for non-Angular files.
343    pub angular_used_selectors: Vec<String>,
344    /// Angular component class names referenced as a route entry or bootstrap
345    /// target: a route `component: Foo` / `loadComponent: () => import().then(m =>
346    /// m.Foo)` value, a `bootstrapApplication(Foo)` argument, or a
347    /// `bootstrap: [Foo]` NgModule entry. These are render-equivalent entry points
348    /// (Angular instantiates them without a template `<tag>`), so the Angular
349    /// `unrendered-component` detector abstains on a component whose class name is
350    /// in the project-wide union. A plain `declarations: [...]` / `imports: [...]`
351    /// registration is intentionally NOT harvested here (that is the dead case the
352    /// rule catches). Empty for non-Angular files.
353    pub angular_entry_component_refs: Vec<String>,
354    /// `true` when this file dynamically renders an Angular component fallow
355    /// cannot attribute to a literal class reference: a
356    /// `ViewContainerRef.createComponent(...)` / `*.createComponent(<ident>)`
357    /// call, or an `*ngComponentOutlet` template binding. The Angular
358    /// `unrendered-component` detector abstains project-wide when ANY reachable
359    /// module sets this (mirroring `unprovided-inject`'s `has_dynamic_provide`),
360    /// since a component could be rendered by a non-literal class reference.
361    pub has_dynamic_component_render: bool,
362    /// `true` when `defineEmits` was called with an unharvestable argument (a
363    /// type-reference type argument such as `defineEmits<MyEmits>()`, a
364    /// non-literal runtime form, or an unbound `defineEmits([...])`). The
365    /// detector abstains on the whole file so an emit is never falsely flagged.
366    pub has_unharvestable_emits: bool,
367    /// `true` when an `emit(<nonLiteral>)` call was seen (the emitted event name
368    /// cannot be known statically). The detector abstains on the whole file.
369    pub has_dynamic_emit: bool,
370    /// `true` when the `defineEmits` return binding was used as a WHOLE value
371    /// (passed to a function, returned, or spread), which can emit any event
372    /// opaquely. The detector abstains on the whole file.
373    pub has_emit_whole_object_use: bool,
374    /// SvelteKit `load()` return-object keys harvested from a
375    /// `+page.{ts,server.ts,js,server.js}` file's terminal return literal.
376    /// Consumed by the `unused-load-data-key` detector. Empty for every file
377    /// that is not a page-load producer (gated by basename at harvest time).
378    pub load_return_keys: Vec<LoadReturnKey>,
379    /// `true` when this file's `load()` body could not be harvested safely (a
380    /// spread return, a non-object/non-literal return, more than one top-level
381    /// `return`, a computed key, or a wrapped/re-exported `load`). The detector
382    /// abstains on the whole file so a key is never falsely flagged.
383    pub has_unharvestable_load: bool,
384    /// `true` when this file passes the whole `data` object opaquely (script
385    /// `const X = data`, `fn(data)` / `fn(...data)`, or template `data={data}` /
386    /// `{...data}` in a route component), so a child can read arbitrary keys the
387    /// detector cannot see. Name-gated on the `data` binding. Read ONLY by the
388    /// `unused-load-data-key` detector, so capturing it for all files is
389    /// byte-identity-safe. See FP-1 in the plan.
390    pub has_load_data_whole_use: bool,
391    /// `true` when this file uses the whole `page.data` / `$page.data` store
392    /// object opaquely (e.g. `Object.values(page.data)`, `{...$page.data}`), so a
393    /// reflective read could consume any route's key. Drives the
394    /// `unused-load-data-key` detector's project-wide abstain. Derived by
395    /// `prepare_analysis_facts` from `whole_object_uses` before the owned release
396    /// path clears that vector. It is never cached and is recomputed each run from
397    /// the cached `whole_object_uses`. Reassignment forms
398    /// (`const all = $page.data`) are not whole-object-tracked and stay out of
399    /// scope, matching the syntactic analyzer's conservative posture.
400    pub has_page_data_store_whole_use: bool,
401    /// `true` when a React Router or Remix route consumes the whole
402    /// `useLoaderData()` result opaquely. Derived by `prepare_analysis_facts`
403    /// from the synthetic route-loader marker before the owned release path
404    /// clears `whole_object_uses`. It is recomputed from cached extraction data.
405    pub has_route_loader_data_whole_use: bool,
406    /// React/JSX component definitions: functions/arrows whose body returns JSX.
407    /// Captured only for `.jsx`/`.tsx` files when a React/Preact dependency is
408    /// plausible. Consumed by the React `unused-component-prop` arm and the
409    /// complexity-fold phase. Empty for non-React files.
410    pub component_functions: Vec<ComponentFunction>,
411    /// React component props (reuses the shared `ComponentProp` struct). For
412    /// React, `used_in_template` is always false and `used_in_script` means
413    /// used-in-body. Empty for non-React files.
414    pub react_props: Vec<ComponentProp>,
415    /// React hook call sites (`useState` / `useEffect` / `useMemo` /
416    /// `useCallback` / custom `use*`). Drives hook-density complexity context.
417    /// Empty for non-React files.
418    pub hook_uses: Vec<HookUse>,
419    /// React render edges: one component rendering another. Captured with the
420    /// child's written name; child-to-`FileId` resolution is deferred to graph
421    /// build. Empty for non-React files.
422    pub render_edges: Vec<RenderEdge>,
423    /// Svelte custom events dispatched via `dispatch('<name>')` where `dispatch`
424    /// is the binding from `const dispatch = createEventDispatcher()`. Consumed
425    /// by the `unused-svelte-event` detector to flag an event dispatched here but
426    /// listened to nowhere project-wide. Each entry carries the literal event
427    /// name and its span. Empty for every non-Svelte file.
428    pub svelte_dispatched_events: Vec<DispatchedEvent>,
429    /// Svelte custom-event listener names harvested from template `on:<name>`
430    /// bindings on COMPONENT tags (PascalCase tag names). Lowercase DOM-element
431    /// `on:click` is a DOM event, not a custom event, and is excluded. Unioned
432    /// project-wide by the `unused-svelte-event` detector to build the liberal
433    /// "listened" set. Empty for every non-Svelte file.
434    pub svelte_listened_events: Vec<String>,
435    /// `true` when a `dispatch(<nonLiteral>)` call was seen (the dispatched event
436    /// name cannot be known statically), or the `dispatch` binding was used as a
437    /// whole value (passed / returned). The `unused-svelte-event` detector
438    /// abstains on the whole component so an event is never falsely flagged.
439    pub has_dynamic_dispatch: bool,
440}
441
442impl ModuleInfo {
443    /// A fully-zeroed `ModuleInfo` for the given file.
444    ///
445    /// Fixture builders and non-JS extraction paths start from this and set
446    /// only the fields they care about via struct-update syntax:
447    /// `ModuleInfo { exports: vec![..], ..ModuleInfo::empty(file_id) }`.
448    #[must_use]
449    pub fn empty(file_id: FileId) -> Self {
450        Self {
451            file_id,
452            exports: Arc::default(),
453            imports: Vec::new(),
454            re_exports: Vec::new(),
455            dynamic_imports: Vec::new(),
456            dynamic_import_patterns: Vec::new(),
457            require_calls: Vec::new(),
458            package_path_references: Box::default(),
459            type_package_references: Box::default(),
460            bin_path_references: Box::default(),
461            package_resolve_sites: Box::default(),
462            member_accesses: Arc::default(),
463            semantic_facts: Arc::default(),
464            whole_object_uses: Arc::default(),
465            has_cjs_exports: false,
466            has_angular_component_template_url: false,
467            content_hash: 0,
468            parse_error_count: 0,
469            parse_panicked: false,
470            parse_nesting_too_deep: false,
471            suppressions: Vec::new(),
472            unknown_suppression_kinds: Vec::new(),
473            range_marker_problems: Vec::new(),
474            inline_threshold_overrides: InlineThresholdOverrides::default(),
475            unused_import_bindings: Vec::new(),
476            type_referenced_import_bindings: Vec::new(),
477            value_referenced_import_bindings: Vec::new(),
478            line_offsets: Vec::new(),
479            complexity: Vec::new(),
480            flag_uses: Vec::new(),
481            flag_registry_facts: None,
482            class_heritage: Vec::new(),
483            exported_factory_returns: Arc::default(),
484            exported_factory_return_object_shapes: Arc::default(),
485            type_member_types: Arc::default(),
486            injection_tokens: Vec::new(),
487            local_type_declarations: Vec::new(),
488            public_signature_type_references: Vec::new(),
489            namespace_object_aliases: Vec::new(),
490            iconify_prefixes: Vec::new(),
491            iconify_icon_names: Vec::new(),
492            auto_import_candidates: Vec::new(),
493            directives: Vec::new(),
494            client_only_dynamic_import_spans: Vec::new(),
495            env_reads: Vec::new(),
496            security_sinks: Vec::new(),
497            security_sinks_skipped: 0,
498            security_unresolved_callee_sites: Vec::new(),
499            inert_function_exports: Vec::new(),
500            tainted_bindings: Vec::new(),
501            sanitized_sink_args: Vec::new(),
502            security_control_sites: Vec::new(),
503            callee_uses: Vec::new(),
504            command_invocations: Vec::new(),
505            imported_call_sites: Arc::default(),
506            import_binding_references: Arc::default(),
507            misplaced_directives: Vec::new(),
508            inline_server_action_exports: Vec::new(),
509            di_key_sites: Vec::new(),
510            has_dynamic_provide: false,
511            is_server_action_module: false,
512            has_global_declarations: false,
513            triple_slash_reference_paths: Box::default(),
514            jsx_runtime_from_config: false,
515            referenced_import_bindings: Vec::new(),
516            component_props: Vec::new(),
517            component_contracts: None,
518            effect_facts: None,
519            function_contracts: None,
520            has_props_attrs_fallthrough: false,
521            has_define_expose: false,
522            has_define_model: false,
523            has_unharvestable_props: false,
524            component_emits: Vec::new(),
525            angular_inputs: Vec::new(),
526            angular_outputs: Vec::new(),
527            has_unharvestable_emits: false,
528            has_dynamic_emit: false,
529            has_emit_whole_object_use: false,
530            load_return_keys: Vec::new(),
531            has_unharvestable_load: false,
532            has_load_data_whole_use: false,
533            has_page_data_store_whole_use: false,
534            has_route_loader_data_whole_use: false,
535            component_functions: Vec::new(),
536            react_props: Vec::new(),
537            hook_uses: Vec::new(),
538            render_edges: Vec::new(),
539            svelte_dispatched_events: Vec::new(),
540            svelte_listened_events: Vec::new(),
541            angular_component_selectors: Vec::new(),
542            registered_custom_elements: Vec::new(),
543            used_custom_element_tags: Vec::new(),
544            angular_used_selectors: Vec::new(),
545            angular_entry_component_refs: Vec::new(),
546            has_dynamic_component_render: false,
547            has_dynamic_dispatch: false,
548        }
549    }
550
551    /// Derive compact detector facts from resolution payload before sharing.
552    ///
553    /// Shared analysis sessions keep the source payload for later graph runs,
554    /// but detectors still require the same derived facts that the owned
555    /// release path computes before clearing that payload.
556    #[doc(hidden)]
557    pub fn prepare_analysis_facts(&mut self) {
558        // The analyze-layer `unrendered-component` detector needs the compact
559        // complement of imports and unused bindings after resolution.
560        self.referenced_import_bindings = self
561            .imports
562            .iter()
563            .map(|import| import.local_name.clone())
564            .filter(|name| !name.is_empty() && !self.unused_import_bindings.contains(name))
565            .collect();
566        self.referenced_import_bindings.sort_unstable();
567        self.referenced_import_bindings.dedup();
568
569        // The `unused-load-data-key` detector needs the project-wide signal
570        // after `whole_object_uses` is released from owned artifacts.
571        self.has_page_data_store_whole_use = self
572            .whole_object_uses
573            .iter()
574            .any(|name| name == "page.data" || name == "$page.data");
575        self.has_route_loader_data_whole_use = self
576            .whole_object_uses
577            .iter()
578            .any(|name| name == "$fallow.routeLoaderData");
579    }
580
581    /// Release extraction payload that resolution has already copied into the graph.
582    ///
583    /// This keeps fields needed by analysis, health, security, LSP, coverage,
584    /// and hash drift checks, while dropping vectors that otherwise duplicate
585    /// data owned by `ResolvedModule` or already credited into the module graph.
586    pub fn release_resolution_payload(&mut self) {
587        self.prepare_analysis_facts();
588        Self::release_vec(&mut self.dynamic_imports);
589        Self::release_vec(&mut self.require_calls);
590        Self::release_boxed_slice(&mut self.package_path_references);
591        Self::release_boxed_slice(&mut self.type_package_references);
592        Self::release_boxed_slice(&mut self.bin_path_references);
593        Self::release_arc_slice(&mut self.whole_object_uses);
594        Self::release_arc_slice(&mut self.import_binding_references);
595        Self::release_vec(&mut self.unused_import_bindings);
596        Self::release_vec(&mut self.type_referenced_import_bindings);
597        Self::release_vec(&mut self.value_referenced_import_bindings);
598        Self::release_vec(&mut self.namespace_object_aliases);
599        Self::release_vec(&mut self.auto_import_candidates);
600    }
601
602    fn release_vec<T>(values: &mut Vec<T>) {
603        *values = Vec::new();
604    }
605
606    fn release_boxed_slice<T>(values: &mut Box<[T]>) {
607        *values = Box::default();
608    }
609
610    /// Drop this module's refcount; the allocation itself is freed only once
611    /// the sharing `ResolvedModule` releases its clone too.
612    fn release_arc_slice<T>(values: &mut Arc<[T]>) {
613        *values = Arc::default();
614    }
615}
616
617#[path = "extract_sink_values.rs"]
618mod sink_values;
619pub use sink_values::{SecurityUrlShape, SinkCallOptions, SinkLiteralValue, SinkObjectProperty};
620#[path = "extract_env.rs"]
621mod env;
622pub use env::*;
623#[path = "extract_security.rs"]
624mod security;
625pub use security::*;
626
627/// One alias entry tying an exported object's dotted property path to a namespace import.
628#[derive(Debug, Clone)]
629pub struct NamespaceObjectAlias {
630    /// Canonical export name.
631    pub via_export_name: String,
632    /// Dotted suffix of the property path relative to the export.
633    pub suffix: String,
634    /// Local name of the namespace import.
635    pub namespace_local: String,
636}
637
638/// Compute a table of line-start byte offsets from source text.
639#[must_use]
640#[expect(
641    clippy::cast_possible_truncation,
642    reason = "source files are practically < 4GB"
643)]
644pub fn compute_line_offsets(source: &str) -> Vec<u32> {
645    let mut offsets = vec![0u32];
646    for (i, byte) in source.bytes().enumerate() {
647        if byte == b'\n' {
648            debug_assert!(
649                u32::try_from(i + 1).is_ok(),
650                "source file exceeds u32::MAX bytes: line offsets would overflow"
651            );
652            offsets.push((i + 1) as u32);
653        }
654    }
655    offsets
656}
657
658/// Convert a byte offset to a 1-based line number and 0-based byte column.
659#[must_use]
660#[expect(
661    clippy::cast_possible_truncation,
662    reason = "line count is bounded by source size"
663)]
664pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
665    let line_idx = match line_offsets.binary_search(&byte_offset) {
666        Ok(idx) => idx,
667        Err(idx) => idx.saturating_sub(1),
668    };
669    let line = line_idx as u32 + 1;
670    let col = byte_offset - line_offsets[line_idx];
671    (line, col)
672}
673
674/// True when `name` identifies a synthetic template-family complexity unit:
675/// the per-file `<template>` unit every framework template scanner emits, or a
676/// Svelte `<snippet:NAME>` unit. These units are exercised only through their
677/// component, carry no directly measurable test coverage, and are therefore
678/// excluded from the CRAP dimension. The `<component>` rollup is NOT part of
679/// this family: it is an aggregate over class + template findings, not an
680/// extracted unit.
681#[must_use]
682pub fn is_synthetic_template_unit(name: &str) -> bool {
683    name == "<template>" || name.starts_with("<snippet:")
684}
685
686/// Placeholder name of a function expression that has no name from its
687/// declaration, its binding, a key, or its call context.
688pub const ANONYMOUS_FUNCTION_NAME: &str = "<anonymous>";
689
690/// Placeholder name of an arrow function that has no name from its binding, a
691/// key, or its call context.
692pub const ANONYMOUS_ARROW_NAME: &str = "<arrow>";
693
694/// True when `name` is the placeholder of a function without a name. Two
695/// functions that share a placeholder are not the same function.
696#[must_use]
697pub fn is_anonymous_function_name(name: &str) -> bool {
698    name == ANONYMOUS_FUNCTION_NAME || name == ANONYMOUS_ARROW_NAME
699}
700
701/// Emitted name of the synthetic module-scope complexity unit.
702pub const MODULE_UNIT_NAME: &str = "<module>";
703
704/// True when `name` identifies the synthetic per-file module-scope unit.
705///
706/// Extraction pushes one root frame per program so decision points outside
707/// every function (an environment guard, a top-level `??` / `||` default, an
708/// `?.` access on a config object) are counted instead of silently dropped.
709/// The unit is emitted only when it actually branches, and it is
710/// aggregate-only: it feeds vital signs, file scores, and branching
711/// conservation, and never becomes a user-facing finding. "Extract a helper"
712/// is not advice that applies to module scope, so the unit reports the
713/// quantity without asking anyone to act on it.
714///
715/// Deliberately NOT part of [`is_synthetic_template_unit`]. That predicate
716/// carries template-family CRAP, suppression, and display semantics, and
717/// [`FileBranching::from_units`] filters on it: folding `<module>` in would
718/// exclude module-scope branching from the branching totals, which is the
719/// blind spot this unit exists to close.
720#[must_use]
721pub fn is_synthetic_module_unit(name: &str) -> bool {
722    name == MODULE_UNIT_NAME
723}
724
725#[path = "extract_function_metrics.rs"]
726mod function_metrics;
727pub use function_metrics::*;
728
729#[path = "extract_css_analytics.rs"]
730mod css_analytics;
731pub use css_analytics::*;
732
733#[path = "extract_flags.rs"]
734mod flags;
735pub use flags::*;
736
737/// The runtime mechanism used to load a module.
738#[derive(
739    Debug,
740    Clone,
741    Copy,
742    PartialEq,
743    Eq,
744    Hash,
745    serde::Serialize,
746    serde::Deserialize,
747    bitcode::Encode,
748    bitcode::Decode,
749)]
750#[repr(u8)]
751pub enum ModuleLoadMechanism {
752    /// ECMAScript module loading through imports, re-exports, or import globs.
753    EsModule = 0,
754    /// CommonJS module loading through `require()` or `require.context`.
755    CommonJsRequire = 1,
756}
757
758#[path = "extract_load_kind.rs"]
759mod load_kind;
760pub use load_kind::ImportLoadKind;
761
762/// Visibility tag from JSDoc/TSDoc comments that suppresses unused-export detection.
763#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
764#[serde(rename_all = "lowercase")]
765#[repr(u8)]
766pub enum VisibilityTag {
767    /// No visibility tag present.
768    #[default]
769    None = 0,
770    /// `@public` or `@api public` -- part of the public API surface.
771    Public = 1,
772    /// `@internal` -- exported for internal use (sister packages, build tools).
773    Internal = 2,
774    /// `@beta` -- public but unstable, may change without notice.
775    Beta = 3,
776    /// `@alpha` -- early preview, may change drastically without notice.
777    Alpha = 4,
778    /// `@expected-unused` -- intentionally unused, should warn when it becomes used.
779    ExpectedUnused = 5,
780}
781
782impl VisibilityTag {
783    /// Whether this tag permanently suppresses unused-export detection.
784    /// `ExpectedUnused` is handled separately (conditionally suppresses,
785    /// reports stale when the export becomes used).
786    pub const fn suppresses_unused(self) -> bool {
787        matches!(
788            self,
789            Self::Public | Self::Internal | Self::Beta | Self::Alpha
790        )
791    }
792
793    /// For serde `skip_serializing_if`.
794    pub fn is_none(&self) -> bool {
795        matches!(self, Self::None)
796    }
797}
798
799/// An export declaration.
800#[derive(Debug, Clone, serde::Serialize)]
801pub struct ExportInfo {
802    /// The exported name (named or default).
803    pub name: ExportName,
804    /// The local binding name, if different from the exported name.
805    pub local_name: Option<String>,
806    /// Whether this is a type-only export (`export type`).
807    pub is_type_only: bool,
808    /// Whether this export is registered through a runtime side effect at module load time.
809    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
810    pub is_side_effect_used: bool,
811    /// Visibility tag from JSDoc/TSDoc comment.
812    #[serde(default, skip_serializing_if = "VisibilityTag::is_none")]
813    pub visibility: VisibilityTag,
814    /// Human-authored reason on `@expected-unused -- <reason>`, when present.
815    #[serde(default, skip_serializing_if = "Option::is_none")]
816    pub expected_unused_reason: Option<String>,
817    /// Whether the leading JSDoc carries a `@deprecated` tag. Orthogonal to
818    /// `visibility`: `@public @deprecated` is a normal combination.
819    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
820    pub deprecated: bool,
821    /// Plain-text `@deprecated` message, capped at
822    /// `DEPRECATED_REASON_MAX_CHARS` characters. `None` for a bare tag.
823    #[serde(default, skip_serializing_if = "Option::is_none")]
824    pub deprecated_reason: Option<Box<str>>,
825    /// Source span of the export declaration.
826    #[serde(serialize_with = "serialize_span")]
827    pub span: Span,
828    /// Members of this export (for enums, classes, and namespaces).
829    #[serde(default, skip_serializing_if = "Vec::is_empty")]
830    pub members: Vec<MemberInfo>,
831    /// The local name of the parent class from `extends` clause, if any.
832    #[serde(default, skip_serializing_if = "Option::is_none")]
833    pub super_class: Option<String>,
834}
835
836#[path = "extract_class_heritage.rs"]
837mod class_heritage;
838pub use class_heritage::ClassHeritageInfo;
839
840/// One resolved property of an object-literal factory return: a dotted property
841/// path mapped to the class the value at that path is an instance of.
842///
843/// `return { invoke: { orders: factory.ordersPage } }` records
844/// `{ property_path: "invoke.orders", class_local_name: "OrdersPage" }`. The class
845/// name is the factory module's own LOCAL name, resolved at analyze time through the
846/// factory module's imports to the real class export. See issue #1858.
847#[derive(
848    Debug,
849    Clone,
850    serde::Serialize,
851    serde::Deserialize,
852    bitcode::Encode,
853    bitcode::Decode,
854    PartialEq,
855    Eq,
856)]
857pub struct FactoryReturnObjectProperty {
858    /// Dotted property path from the returned object literal (`orders`, `invoke.orders`).
859    pub property_path: String,
860    /// The property value's class local name within the factory module.
861    pub class_local_name: String,
862}
863
864/// An exported factory function that returns an object literal whose property
865/// values are class instances, joined to its public export name.
866///
867/// A cross-module `const ui = createUi(); ui.orders.member` consumer emits a
868/// `FactoryReturnObjectPropertyAccess` fact; the analyze layer resolves `export_name`
869/// through the consumer's imports to this module, matches `property_path`, and credits
870/// `member` on the resolved class (gated on it being a class with members). See issue #1858.
871#[derive(
872    Debug,
873    Clone,
874    serde::Serialize,
875    serde::Deserialize,
876    bitcode::Encode,
877    bitcode::Decode,
878    PartialEq,
879    Eq,
880)]
881pub struct FactoryReturnObjectShapeExport {
882    /// Public export name (honors `export { createUi as createOrdersUi }`).
883    pub export_name: String,
884    /// Resolved `(property_path -> class_local_name)` entries for the returned literal.
885    pub properties: Box<[FactoryReturnObjectProperty]>,
886}
887
888/// A module-scope declaration that can be used as a TypeScript type.
889#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
890pub struct LocalTypeDeclaration {
891    /// Local declaration name.
892    pub name: String,
893    /// Declaration identifier span.
894    #[serde(serialize_with = "serialize_span")]
895    pub span: Span,
896}
897
898/// A reference from an exported symbol's public signature to a type name.
899#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
900pub struct PublicSignatureTypeReference {
901    /// Exported symbol whose signature contains the reference.
902    pub export_name: String,
903    /// Referenced type name. Qualified names are reduced to their root identifier.
904    pub type_name: String,
905    /// Reference span.
906    #[serde(serialize_with = "serialize_span")]
907    pub span: Span,
908    /// True when the reference comes from a `satisfies` clause. The clause
909    /// checks the value but does not change the exported type, so the type is
910    /// in use but is not a private type leak.
911    #[serde(skip_serializing_if = "std::ops::Not::not")]
912    pub from_satisfies: bool,
913}
914
915/// A member of an enum, class, or namespace.
916#[derive(Debug, Clone, serde::Serialize)]
917pub struct MemberInfo {
918    /// Member name.
919    pub name: String,
920    /// The kind of member (enum, class method/property, or namespace member).
921    pub kind: MemberKind,
922    /// Source span of the member declaration.
923    #[serde(serialize_with = "serialize_span")]
924    pub span: Span,
925    /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
926    /// Decorated members are used by frameworks at runtime and should not be
927    /// flagged as unused class members, unless every decorator on the member
928    /// is opted out via `FallowConfig.ignore_decorators`.
929    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
930    pub has_decorator: bool,
931    /// Full dotted path of each decorator on this member, in source order.
932    /// `@step("x")` stores `"step"`; `@ns.foo` stores `"ns.foo"`. Empty for
933    /// undecorated members, Angular signal-initializer properties (which set
934    /// `has_decorator` without a literal decorator AST node), and decorators
935    /// whose expression is not an identifier ladder (the entry is the empty
936    /// string in that case, treated as never-matching by the predicate).
937    #[serde(default, skip_serializing_if = "Vec::is_empty")]
938    pub decorator_names: Vec<String>,
939    /// True for a static method that returns a new instance of its class
940    /// (`return new this()`, `return new C()`, or a declared return type `C`).
941    /// Member accesses on the call result credit the class (#346, #387).
942    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
943    pub is_instance_returning_static: bool,
944    /// True for an instance method whose call result is an instance of the
945    /// same class: the declared return type names the class, or the body ends
946    /// with `return this`. The analysis walks fluent chains
947    /// (`Class.factory().setX().setY()`) only through these methods (#387).
948    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
949    pub is_self_returning: bool,
950    /// Root identifier of the class `extends` expression, set only when the
951    /// member has the `override` modifier: `Container` in
952    /// `extends Container<Env>`, `Schema` in `extends Schema.TaggedError<E>()(...)`.
953    /// The analysis credits the member when this root names code outside the
954    /// project, because that code calls the overridden member.
955    #[serde(default, skip_serializing_if = "Option::is_none")]
956    pub override_base: Option<String>,
957    /// True for a class member with the TypeScript `protected` modifier. Only
958    /// the `unused-protected-class-members` rule checks these members. Every
959    /// other consumer that checks class members skips them.
960    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
961    pub is_protected: bool,
962    /// True for a `static` class member, which code with the class value reads.
963    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
964    pub is_static: bool,
965    /// True for `dispose` when the class declares `[Symbol.dispose]` or `[Symbol.asyncDispose]`.
966    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
967    pub pairs_with_symbol_dispose: bool,
968}
969
970/// The kind of member.
971#[derive(
972    Debug,
973    Clone,
974    Copy,
975    PartialEq,
976    Eq,
977    serde::Serialize,
978    serde::Deserialize,
979    bitcode::Encode,
980    bitcode::Decode,
981)]
982#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
983#[serde(rename_all = "snake_case")]
984pub enum MemberKind {
985    /// A TypeScript enum member.
986    EnumMember,
987    /// A class method.
988    ClassMethod,
989    /// A class property.
990    ClassProperty,
991    /// A member exported from a TypeScript namespace.
992    NamespaceMember,
993    /// A member declared by a store object (Pinia `state` / `getters` /
994    /// `actions` key, or a setup-store returned key). Cross-graph dead-member
995    /// detection: a store member never accessed by any consumer project-wide.
996    StoreMember,
997}
998
999/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
1000#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
1001pub struct MemberAccess {
1002    /// The identifier being accessed (the import name).
1003    pub object: String,
1004    /// The member being accessed.
1005    pub member: String,
1006}
1007
1008/// Direct export declarations that TypeScript treats as one merged symbol.
1009///
1010/// Spans identify the exact declaration slots without conflating unrelated
1011/// type/value declarations that happen to share a name.
1012#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1013#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1014pub struct DeclarationMergeFact {
1015    /// Identifier spans for the declarations in this merge group.
1016    pub export_spans: Vec<(u32, u32)>,
1017}
1018
1019/// A default import binding consumed outside a statically known member access.
1020///
1021/// Resolution decides whether the target is an object-shaped module such as a
1022/// CSS Module or a proven static CommonJS object map. Keeping this fact
1023/// target-agnostic lets aliases and extensionless specifiers use the resolved
1024/// target path without broadening ordinary default-import behavior.
1025#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1026#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1027pub struct DefaultImportWholeObjectUseFact {
1028    /// Local binding name in the importing module.
1029    pub local_name: String,
1030}
1031
1032#[path = "extract_semantic.rs"]
1033mod semantic;
1034pub use semantic::{DecoratorMetadataReferenceFact, SemanticFact};
1035
1036pub use crate::extract_namespace_member_uses::{HolderValueFact, NamespaceMemberUseFact};
1037
1038/// A static member name that a runtime probe checks on an untyped value.
1039#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1040#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1041pub struct MemberNameProbeFact {
1042    /// The probed member name.
1043    pub name: String,
1044}
1045
1046/// Deferred class provenance owned by the module declaring an object factory.
1047#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1048#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1049pub enum FactoryPropertySource {
1050    /// A property path through a named type in the factory's module.
1051    TypedProperty {
1052        /// Named receiver type in the producer module.
1053        type_name: String,
1054        /// Remaining path through the receiver type.
1055        property_path: String,
1056    },
1057    /// A synchronous function call in the factory's module.
1058    FunctionReturn {
1059        /// Function binding in the producer module.
1060        callee_name: String,
1061    },
1062    /// A proven instance-returning static class method.
1063    StaticFactoryReturn {
1064        /// Class binding in the producer module.
1065        callee_object: String,
1066        /// Statically named instance-returning method.
1067        callee_method: String,
1068    },
1069    /// A class proven in the object factory's own module.
1070    LocalClass {
1071        /// Local class binding resolved relative to the factory module.
1072        class_local_name: String,
1073    },
1074    /// Return of the callback at this ordinal in the proven helper declaration.
1075    CallbackParameterReturn {
1076        /// Zero-based formal parameter ordinal.
1077        parameter_index: u32,
1078    },
1079}
1080
1081/// Callback-origin member use, joined with the callee module's property source.
1082#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1083#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1084pub struct CallbackFactoryPropertyAccessFact {
1085    /// Callee import binding in the caller module.
1086    pub callee_name: String,
1087    /// Static export selected from a namespace import, if present.
1088    pub callee_member: Option<String>,
1089    /// Requested path in the wrapper's returned value.
1090    pub property_path: String,
1091    /// Requested member on the callback result.
1092    pub member: String,
1093    /// A property write permits only the canonical Vue getter contract.
1094    pub vue_only: bool,
1095    /// Ordinary assigned value, ignored by a canonical Vue setter contract.
1096    pub assigned_class: Option<String>,
1097    /// Callback ordinal and class origin interpreted in the caller module.
1098    pub arguments: Vec<CallbackFactoryArgument>,
1099}
1100
1101/// Proven callback result owned by a factory consumer's module.
1102#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1103#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1104pub struct CallbackFactoryArgument {
1105    /// Zero-based actual argument ordinal.
1106    pub parameter_index: u32,
1107    /// Class binding resolved in the consumer module.
1108    pub class_local_name: String,
1109    /// This argument is an options object with a proven `get` callback.
1110    pub getter: bool,
1111    /// No mutable capture makes a lazy invocation select another class.
1112    pub lazy_safe: bool,
1113}
1114
1115/// An exported object factory's deferred property receiver.
1116#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1117#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1118pub struct FactoryReturnObjectPropertySourceFact {
1119    /// Public factory export name.
1120    pub factory_export_name: String,
1121    /// Path within the returned object, separate from any source property path.
1122    pub property_path: String,
1123    /// Names interpreted relative to this fact's owning module.
1124    pub source: FactoryPropertySource,
1125}
1126
1127/// The load kind of the dynamic imports or patterns that start at `span_start`.
1128#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1129#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1130pub struct ImportLoadKindOverrideFact {
1131    /// Byte offset of the call or `new` expression that records the edge.
1132    pub span_start: u32,
1133    /// The load kind of every edge that the expression records.
1134    pub kind: ImportLoadKind,
1135}
1136
1137/// The Module Federation runtime function that a call names.
1138#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1139#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1140#[serde(rename_all = "camelCase")]
1141pub enum FederationRuntimeCall {
1142    /// `registerRemotes([{ name, entry }])`.
1143    RegisterRemotes,
1144    /// `loadRemote('remote/module')`.
1145    LoadRemote,
1146    /// `init({ remotes: [{ name, entry }] })`.
1147    /// Appended because bitcode encodes enum variants by ordinal.
1148    Init,
1149    /// `createInstance({ remotes: [{ name, entry }] })`.
1150    CreateInstance,
1151}
1152
1153impl FederationRuntimeCall {
1154    /// The function name as the source writes it.
1155    #[must_use]
1156    pub const fn name(self) -> &'static str {
1157        match self {
1158            Self::RegisterRemotes => "registerRemotes",
1159            Self::LoadRemote => "loadRemote",
1160            Self::Init => "init",
1161            Self::CreateInstance => "createInstance",
1162        }
1163    }
1164}
1165
1166/// One remote that a Module Federation runtime call names.
1167///
1168/// `remote` is the remote alias when the argument is a static literal, and
1169/// `None` when the call receives a value that static analysis cannot read.
1170#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1171#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1172pub struct FederationRuntimeRemoteFact {
1173    /// The runtime function the call names.
1174    pub call: FederationRuntimeCall,
1175    /// The remote alias the call names, or `None` for a non-literal argument.
1176    pub remote: Option<String>,
1177}
1178
1179#[path = "extract_semantic_view.rs"]
1180mod semantic_view;
1181pub use semantic_view::*;
1182
1183#[path = "extract_member_facts.rs"]
1184mod member_facts;
1185pub use member_facts::*;
1186
1187#[path = "extract_components.rs"]
1188mod components;
1189pub use components::*;
1190
1191#[expect(
1192    clippy::trivially_copy_pass_by_ref,
1193    reason = "serde serialize_with requires &T"
1194)]
1195fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
1196    use serde::ser::SerializeMap;
1197    let mut map = serializer.serialize_map(Some(2))?;
1198    map.serialize_entry("start", &span.start)?;
1199    map.serialize_entry("end", &span.end)?;
1200    map.end()
1201}
1202
1203/// Export identifier.
1204#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1205pub enum ExportName {
1206    /// A named export (e.g., `export const foo`).
1207    Named(String),
1208    /// The default export.
1209    Default,
1210}
1211
1212impl ExportName {
1213    /// Compare against a string without allocating (avoids `to_string()`).
1214    #[must_use]
1215    pub fn matches_str(&self, s: &str) -> bool {
1216        match self {
1217            Self::Named(n) => n == s,
1218            Self::Default => s == "default",
1219        }
1220    }
1221}
1222
1223impl std::fmt::Display for ExportName {
1224    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1225        match self {
1226            Self::Named(n) => write!(f, "{n}"),
1227            Self::Default => write!(f, "default"),
1228        }
1229    }
1230}
1231
1232/// An import declaration.
1233#[derive(Debug, Clone)]
1234pub struct ImportInfo {
1235    /// The import specifier (e.g., `./utils` or `react`).
1236    pub source: String,
1237    /// How the symbol is imported (named, default, namespace, or side-effect).
1238    pub imported_name: ImportedName,
1239    /// The local binding name in the importing module.
1240    pub local_name: String,
1241    /// Whether this is a type-only import (`import type`).
1242    pub is_type_only: bool,
1243    /// Whether this whole-module import forwards type meanings only.
1244    ///
1245    /// Set for `export type *` and `export type * as ns` inside a
1246    /// `declare module '...'` body (issue #2375). Those forms record the same
1247    /// bindingless whole-module shape the plain ambient star records
1248    /// (issue #2357), but the star they stand for erases every value meaning,
1249    /// so the graph credits the target's star surface in the type namespace
1250    /// alone. Every other import leaves this false: `is_type_only` already
1251    /// decides their namespace on its own.
1252    pub is_type_only_star: bool,
1253    /// Whether this import originated from a CSS-context.
1254    pub from_style: bool,
1255    /// Source span of the import declaration.
1256    pub span: Span,
1257    /// Span of the source string literal used by the LSP to highlight the specifier.
1258    pub source_span: Span,
1259}
1260
1261/// How a symbol is imported.
1262#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1263pub enum ImportedName {
1264    /// A named import (e.g., `import { foo }`).
1265    Named(String),
1266    /// A default import (e.g., `import React`).
1267    Default,
1268    /// A namespace import (e.g., `import * as utils`).
1269    Namespace,
1270    /// A side-effect import (e.g., `import './styles.css'`).
1271    SideEffect,
1272}
1273
1274#[cfg(target_pointer_width = "64")]
1275const _: () = assert!(std::mem::size_of::<ExportInfo>() == 152);
1276#[cfg(target_pointer_width = "64")]
1277const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
1278#[cfg(target_pointer_width = "64")]
1279const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
1280#[cfg(target_pointer_width = "64")]
1281const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
1282#[cfg(target_pointer_width = "64")]
1283const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
1284#[cfg(target_pointer_width = "64")]
1285const _: () = assert!(std::mem::size_of::<SemanticFact>() == 80);
1286#[cfg(target_pointer_width = "64")]
1287const _: () = assert!(std::mem::size_of::<SinkSite>() == 224);
1288#[cfg(target_pointer_width = "64")]
1289const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 1624);
1290#[cfg(target_pointer_width = "64")]
1291const _: () = assert!(std::mem::size_of::<ImportBindingReference>() == 64);
1292#[cfg(target_pointer_width = "64")]
1293const _: () = assert!(std::mem::size_of::<TypeMemberTypeEntry>() == 72);
1294
1295#[path = "extract_re_export.rs"]
1296mod re_export;
1297pub use re_export::ReExportInfo;
1298
1299#[path = "extract_dynamic_pattern.rs"]
1300mod dynamic_pattern;
1301pub use dynamic_pattern::DynamicImportPattern;
1302
1303#[path = "extract_dynamic_import.rs"]
1304mod dynamic_import;
1305pub use dynamic_import::DynamicImportInfo;
1306
1307/// A `require()` call.
1308#[derive(Debug, Clone)]
1309pub struct RequireCallInfo {
1310    /// The require specifier.
1311    pub source: String,
1312    /// Source span of the `require()` call.
1313    pub span: Span,
1314    /// Span of the string-literal argument with quotes (`'./x'`), which anchors an
1315    /// `unresolved-import` diagnostic. `Span::default()` for a non-literal argument.
1316    pub source_span: Span,
1317    /// Names destructured from the `require()` result.
1318    pub destructured_names: Vec<String>,
1319    /// The `(key, local)` pair of each destructured identifier property:
1320    /// `const { exec: run } = require(...)` gives `("exec", "run")`.
1321    pub destructured_locals: Vec<(String, String)>,
1322    /// The local variable name for `const x = require(...)`.
1323    pub local_name: Option<String>,
1324    /// `true` for `import type X = require('...')`, the one require spelling
1325    /// TypeScript erases entirely: the emitted JavaScript contains no
1326    /// `require` call, so the target is a type-space reference and never a
1327    /// runtime dependency. Always `false` for `const x = require(...)`, which
1328    /// has no type-only spelling. Read by dependency classification so a
1329    /// type-only devDependency is not reported as production usage.
1330    pub is_type_only: bool,
1331}
1332
1333/// Result of parsing all files, including incremental cache statistics.
1334pub struct ParseResult {
1335    /// Extracted module information for all successfully parsed files.
1336    pub modules: Vec<ModuleInfo>,
1337    /// Files discovered with stable IDs but unreadable by the parser.
1338    pub read_failures: Vec<SourceReadFailure>,
1339    /// Files whose extracted modules may be incomplete because of parse diagnostics.
1340    /// Analysis keeps findings visible and attaches caveats to affected findings.
1341    pub parse_degradations: Vec<SourceParseDegradation>,
1342    /// Number of files whose parse results were loaded from cache (unchanged).
1343    pub cache_hits: usize,
1344    /// Number of files that required a full parse (new or changed).
1345    pub cache_misses: usize,
1346    /// Summed wall-clock time of the actual AST parses across all rayon workers.
1347    pub parse_cpu_ms: f64,
1348    /// Files whose bytes were read from disk: every parse, plus every cache
1349    /// hit that had to compare the content hash.
1350    pub files_read: u64,
1351    /// Bytes of source read from disk across all files.
1352    pub source_bytes_read: u64,
1353    /// Source bytes that the CSS comment mask read across all parsed files.
1354    pub css_masked_bytes: u64,
1355    /// Files that the cache served from their metadata alone, without a read
1356    /// of the source, sorted by id. The stored fingerprint of each equals the
1357    /// metadata that the parse read, so a cache writer can keep it.
1358    pub metadata_hits: Vec<FileId>,
1359}
1360
1361/// A discovered source that could not be read as UTF-8 text.
1362#[derive(Debug, Clone, PartialEq, Eq)]
1363pub struct SourceReadFailure {
1364    /// Stable discovery identity retained even though no module was produced.
1365    pub file_id: FileId,
1366    /// Absolute discovered source path.
1367    pub path: PathBuf,
1368    /// Underlying filesystem or UTF-8 decoding error.
1369    pub error: String,
1370}
1371
1372/// A discovered source that was read but did not parse cleanly.
1373///
1374/// The module it produced is still analyzed: dropping it would turn one broken
1375/// file into project-wide silence. The point of carrying the degradation is
1376/// that the imports the file failed to parse credited nothing, so its targets
1377/// can be reported as unused with full confidence unless a consumer is told the
1378/// parse was partial.
1379#[derive(Debug, Clone, PartialEq, Eq)]
1380pub struct SourceParseDegradation {
1381    /// Stable discovery identity of the degraded source.
1382    pub file_id: FileId,
1383    /// Absolute discovered source path.
1384    pub path: PathBuf,
1385    /// Number of parser diagnostics reported for the file.
1386    pub error_count: u32,
1387    /// `true` when the parser abandoned the file instead of recovering.
1388    pub panicked: bool,
1389    /// The nesting cap when the file nests too deep to parse.
1390    pub nesting_limit: Option<u32>,
1391}
1392
1393#[path = "extract_effect.rs"]
1394mod effect;
1395pub use effect::*;
1396#[path = "extract_calls.rs"]
1397mod calls;
1398pub use calls::*;
1399#[path = "extract_function_contracts.rs"]
1400mod function_contracts;
1401pub use function_contracts::*;
1402#[path = "extract_factory.rs"]
1403mod factory;
1404pub use factory::*;
1405#[path = "extract_component_contracts.rs"]
1406mod component_contracts;
1407pub use component_contracts::*;
1408#[path = "extract_type_members.rs"]
1409mod type_members;
1410pub use type_members::*;
1411
1412#[path = "extract_template_members.rs"]
1413mod extract_template_members;
1414use extract_template_members::angular_template_member_names_from_parts;
1415
1416#[cfg(test)]
1417#[path = "extract_tests.rs"]
1418mod tests;