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///
660/// `line_offsets` comes from [`compute_line_offsets`]: it starts at 0 and is
661/// sorted. A list of another shape gives a clamped position and no panic.
662#[must_use]
663#[expect(
664 clippy::cast_possible_truncation,
665 reason = "line count is bounded by source size"
666)]
667pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
668 let line_idx = match line_offsets.binary_search(&byte_offset) {
669 Ok(idx) => idx,
670 Err(idx) => idx.saturating_sub(1),
671 };
672 let line = line_idx as u32 + 1;
673 let line_start = line_offsets.get(line_idx).copied().unwrap_or(0);
674 (line, byte_offset.saturating_sub(line_start))
675}
676
677/// True when `name` identifies a synthetic template-family complexity unit:
678/// the per-file `<template>` unit every framework template scanner emits, or a
679/// Svelte `<snippet:NAME>` unit. These units are exercised only through their
680/// component, carry no directly measurable test coverage, and are therefore
681/// excluded from the CRAP dimension. The `<component>` rollup is NOT part of
682/// this family: it is an aggregate over class + template findings, not an
683/// extracted unit.
684#[must_use]
685pub fn is_synthetic_template_unit(name: &str) -> bool {
686 name == "<template>" || name.starts_with("<snippet:")
687}
688
689/// Placeholder name of a function expression that has no name from its
690/// declaration, its binding, a key, or its call context.
691pub const ANONYMOUS_FUNCTION_NAME: &str = "<anonymous>";
692
693/// Placeholder name of an arrow function that has no name from its binding, a
694/// key, or its call context.
695pub const ANONYMOUS_ARROW_NAME: &str = "<arrow>";
696
697/// True when `name` is the placeholder of a function without a name. Two
698/// functions that share a placeholder are not the same function.
699#[must_use]
700pub fn is_anonymous_function_name(name: &str) -> bool {
701 name == ANONYMOUS_FUNCTION_NAME || name == ANONYMOUS_ARROW_NAME
702}
703
704/// Emitted name of the synthetic module-scope complexity unit.
705pub const MODULE_UNIT_NAME: &str = "<module>";
706
707/// True when `name` identifies the synthetic per-file module-scope unit.
708///
709/// Extraction pushes one root frame per program so decision points outside
710/// every function (an environment guard, a top-level `??` / `||` default, an
711/// `?.` access on a config object) are counted instead of silently dropped.
712/// The unit is emitted only when it actually branches, and it is
713/// aggregate-only: it feeds vital signs, file scores, and branching
714/// conservation, and never becomes a user-facing finding. "Extract a helper"
715/// is not advice that applies to module scope, so the unit reports the
716/// quantity without asking anyone to act on it.
717///
718/// Deliberately NOT part of [`is_synthetic_template_unit`]. That predicate
719/// carries template-family CRAP, suppression, and display semantics, and
720/// [`FileBranching::from_units`] filters on it: folding `<module>` in would
721/// exclude module-scope branching from the branching totals, which is the
722/// blind spot this unit exists to close.
723#[must_use]
724pub fn is_synthetic_module_unit(name: &str) -> bool {
725 name == MODULE_UNIT_NAME
726}
727
728#[path = "extract_function_metrics.rs"]
729mod function_metrics;
730pub use function_metrics::*;
731
732#[path = "extract_css_analytics.rs"]
733mod css_analytics;
734pub use css_analytics::*;
735
736#[path = "extract_flags.rs"]
737mod flags;
738pub use flags::*;
739
740/// The runtime mechanism used to load a module.
741#[derive(
742 Debug,
743 Clone,
744 Copy,
745 PartialEq,
746 Eq,
747 Hash,
748 serde::Serialize,
749 serde::Deserialize,
750 bitcode::Encode,
751 bitcode::Decode,
752)]
753#[repr(u8)]
754pub enum ModuleLoadMechanism {
755 /// ECMAScript module loading through imports, re-exports, or import globs.
756 EsModule = 0,
757 /// CommonJS module loading through `require()` or `require.context`.
758 CommonJsRequire = 1,
759}
760
761#[path = "extract_load_kind.rs"]
762mod load_kind;
763pub use load_kind::ImportLoadKind;
764
765/// Visibility tag from JSDoc/TSDoc comments that suppresses unused-export detection.
766#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
767#[serde(rename_all = "lowercase")]
768#[repr(u8)]
769pub enum VisibilityTag {
770 /// No visibility tag present.
771 #[default]
772 None = 0,
773 /// `@public` or `@api public` -- part of the public API surface.
774 Public = 1,
775 /// `@internal` -- exported for internal use (sister packages, build tools).
776 Internal = 2,
777 /// `@beta` -- public but unstable, may change without notice.
778 Beta = 3,
779 /// `@alpha` -- early preview, may change drastically without notice.
780 Alpha = 4,
781 /// `@expected-unused` -- intentionally unused, should warn when it becomes used.
782 ExpectedUnused = 5,
783}
784
785impl VisibilityTag {
786 /// Whether this tag permanently suppresses unused-export detection.
787 /// `ExpectedUnused` is handled separately (conditionally suppresses,
788 /// reports stale when the export becomes used).
789 pub const fn suppresses_unused(self) -> bool {
790 matches!(
791 self,
792 Self::Public | Self::Internal | Self::Beta | Self::Alpha
793 )
794 }
795
796 /// For serde `skip_serializing_if`.
797 pub fn is_none(&self) -> bool {
798 matches!(self, Self::None)
799 }
800}
801
802/// An export declaration.
803#[derive(Debug, Clone, serde::Serialize)]
804pub struct ExportInfo {
805 /// The exported name (named or default).
806 pub name: ExportName,
807 /// The local binding name, if different from the exported name.
808 pub local_name: Option<String>,
809 /// Whether this is a type-only export (`export type`).
810 pub is_type_only: bool,
811 /// Whether this export is registered through a runtime side effect at module load time.
812 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
813 pub is_side_effect_used: bool,
814 /// Visibility tag from JSDoc/TSDoc comment.
815 #[serde(default, skip_serializing_if = "VisibilityTag::is_none")]
816 pub visibility: VisibilityTag,
817 /// Human-authored reason on `@expected-unused -- <reason>`, when present.
818 #[serde(default, skip_serializing_if = "Option::is_none")]
819 pub expected_unused_reason: Option<String>,
820 /// Whether the leading JSDoc carries a `@deprecated` tag. Orthogonal to
821 /// `visibility`: `@public @deprecated` is a normal combination.
822 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
823 pub deprecated: bool,
824 /// Plain-text `@deprecated` message, capped at
825 /// `DEPRECATED_REASON_MAX_CHARS` characters. `None` for a bare tag.
826 #[serde(default, skip_serializing_if = "Option::is_none")]
827 pub deprecated_reason: Option<Box<str>>,
828 /// Source span of the export declaration.
829 #[serde(serialize_with = "serialize_span")]
830 pub span: Span,
831 /// Members of this export (for enums, classes, and namespaces).
832 #[serde(default, skip_serializing_if = "Vec::is_empty")]
833 pub members: Vec<MemberInfo>,
834 /// The local name of the parent class from `extends` clause, if any.
835 #[serde(default, skip_serializing_if = "Option::is_none")]
836 pub super_class: Option<String>,
837}
838
839#[path = "extract_class_heritage.rs"]
840mod class_heritage;
841pub use class_heritage::ClassHeritageInfo;
842
843/// One resolved property of an object-literal factory return: a dotted property
844/// path mapped to the class the value at that path is an instance of.
845///
846/// `return { invoke: { orders: factory.ordersPage } }` records
847/// `{ property_path: "invoke.orders", class_local_name: "OrdersPage" }`. The class
848/// name is the factory module's own LOCAL name, resolved at analyze time through the
849/// factory module's imports to the real class export. See issue #1858.
850#[derive(
851 Debug,
852 Clone,
853 serde::Serialize,
854 serde::Deserialize,
855 bitcode::Encode,
856 bitcode::Decode,
857 PartialEq,
858 Eq,
859)]
860pub struct FactoryReturnObjectProperty {
861 /// Dotted property path from the returned object literal (`orders`, `invoke.orders`).
862 pub property_path: String,
863 /// The property value's class local name within the factory module.
864 pub class_local_name: String,
865}
866
867/// An exported factory function that returns an object literal whose property
868/// values are class instances, joined to its public export name.
869///
870/// A cross-module `const ui = createUi(); ui.orders.member` consumer emits a
871/// `FactoryReturnObjectPropertyAccess` fact; the analyze layer resolves `export_name`
872/// through the consumer's imports to this module, matches `property_path`, and credits
873/// `member` on the resolved class (gated on it being a class with members). See issue #1858.
874#[derive(
875 Debug,
876 Clone,
877 serde::Serialize,
878 serde::Deserialize,
879 bitcode::Encode,
880 bitcode::Decode,
881 PartialEq,
882 Eq,
883)]
884pub struct FactoryReturnObjectShapeExport {
885 /// Public export name (honors `export { createUi as createOrdersUi }`).
886 pub export_name: String,
887 /// Resolved `(property_path -> class_local_name)` entries for the returned literal.
888 pub properties: Box<[FactoryReturnObjectProperty]>,
889}
890
891/// A module-scope declaration that can be used as a TypeScript type.
892#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
893pub struct LocalTypeDeclaration {
894 /// Local declaration name.
895 pub name: String,
896 /// Declaration identifier span.
897 #[serde(serialize_with = "serialize_span")]
898 pub span: Span,
899}
900
901/// A reference from an exported symbol's public signature to a type name.
902#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
903pub struct PublicSignatureTypeReference {
904 /// Exported symbol whose signature contains the reference.
905 pub export_name: String,
906 /// Referenced type name. Qualified names are reduced to their root identifier.
907 pub type_name: String,
908 /// Reference span.
909 #[serde(serialize_with = "serialize_span")]
910 pub span: Span,
911 /// True when the reference comes from a `satisfies` clause. The clause
912 /// checks the value but does not change the exported type, so the type is
913 /// in use but is not a private type leak.
914 #[serde(skip_serializing_if = "std::ops::Not::not")]
915 pub from_satisfies: bool,
916}
917
918/// A member of an enum, class, or namespace.
919#[derive(Debug, Clone, serde::Serialize)]
920pub struct MemberInfo {
921 /// Member name.
922 pub name: String,
923 /// The kind of member (enum, class method/property, or namespace member).
924 pub kind: MemberKind,
925 /// Source span of the member declaration.
926 #[serde(serialize_with = "serialize_span")]
927 pub span: Span,
928 /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
929 /// Decorated members are used by frameworks at runtime and should not be
930 /// flagged as unused class members, unless every decorator on the member
931 /// is opted out via `FallowConfig.ignore_decorators`.
932 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
933 pub has_decorator: bool,
934 /// Full dotted path of each decorator on this member, in source order.
935 /// `@step("x")` stores `"step"`; `@ns.foo` stores `"ns.foo"`. Empty for
936 /// undecorated members, Angular signal-initializer properties (which set
937 /// `has_decorator` without a literal decorator AST node), and decorators
938 /// whose expression is not an identifier ladder (the entry is the empty
939 /// string in that case, treated as never-matching by the predicate).
940 #[serde(default, skip_serializing_if = "Vec::is_empty")]
941 pub decorator_names: Vec<String>,
942 /// True for a static method that returns a new instance of its class
943 /// (`return new this()`, `return new C()`, or a declared return type `C`).
944 /// Member accesses on the call result credit the class (#346, #387).
945 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
946 pub is_instance_returning_static: bool,
947 /// True for an instance method whose call result is an instance of the
948 /// same class: the declared return type names the class, or the body ends
949 /// with `return this`. The analysis walks fluent chains
950 /// (`Class.factory().setX().setY()`) only through these methods (#387).
951 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
952 pub is_self_returning: bool,
953 /// Root identifier of the class `extends` expression, set only when the
954 /// member has the `override` modifier: `Container` in
955 /// `extends Container<Env>`, `Schema` in `extends Schema.TaggedError<E>()(...)`.
956 /// The analysis credits the member when this root names code outside the
957 /// project, because that code calls the overridden member.
958 #[serde(default, skip_serializing_if = "Option::is_none")]
959 pub override_base: Option<String>,
960 /// True for a class member with the TypeScript `protected` modifier. Only
961 /// the `unused-protected-class-members` rule checks these members. Every
962 /// other consumer that checks class members skips them.
963 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
964 pub is_protected: bool,
965 /// True for a `static` class member, which code with the class value reads.
966 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
967 pub is_static: bool,
968 /// True for `dispose` when the class declares `[Symbol.dispose]` or `[Symbol.asyncDispose]`.
969 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
970 pub pairs_with_symbol_dispose: bool,
971}
972
973/// The kind of member.
974#[derive(
975 Debug,
976 Clone,
977 Copy,
978 PartialEq,
979 Eq,
980 serde::Serialize,
981 serde::Deserialize,
982 bitcode::Encode,
983 bitcode::Decode,
984)]
985#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
986#[serde(rename_all = "snake_case")]
987pub enum MemberKind {
988 /// A TypeScript enum member.
989 EnumMember,
990 /// A class method.
991 ClassMethod,
992 /// A class property.
993 ClassProperty,
994 /// A member exported from a TypeScript namespace.
995 NamespaceMember,
996 /// A member declared by a store object (Pinia `state` / `getters` /
997 /// `actions` key, or a setup-store returned key). Cross-graph dead-member
998 /// detection: a store member never accessed by any consumer project-wide.
999 StoreMember,
1000}
1001
1002/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
1003#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
1004pub struct MemberAccess {
1005 /// The identifier being accessed (the import name).
1006 pub object: String,
1007 /// The member being accessed.
1008 pub member: String,
1009}
1010
1011/// Direct export declarations that TypeScript treats as one merged symbol.
1012///
1013/// Spans identify the exact declaration slots without conflating unrelated
1014/// type/value declarations that happen to share a name.
1015#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1016#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1017pub struct DeclarationMergeFact {
1018 /// Identifier spans for the declarations in this merge group.
1019 pub export_spans: Vec<(u32, u32)>,
1020}
1021
1022/// A default import binding consumed outside a statically known member access.
1023///
1024/// Resolution decides whether the target is an object-shaped module such as a
1025/// CSS Module or a proven static CommonJS object map. Keeping this fact
1026/// target-agnostic lets aliases and extensionless specifiers use the resolved
1027/// target path without broadening ordinary default-import behavior.
1028#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1029#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1030pub struct DefaultImportWholeObjectUseFact {
1031 /// Local binding name in the importing module.
1032 pub local_name: String,
1033}
1034
1035#[path = "extract_semantic.rs"]
1036mod semantic;
1037pub use semantic::{DecoratorMetadataReferenceFact, SemanticFact};
1038
1039pub use crate::extract_namespace_member_uses::{HolderValueFact, NamespaceMemberUseFact};
1040
1041/// A static member name that a runtime probe checks on an untyped value.
1042#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1043#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1044pub struct MemberNameProbeFact {
1045 /// The probed member name.
1046 pub name: String,
1047}
1048
1049/// Deferred class provenance owned by the module declaring an object factory.
1050#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1051#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1052pub enum FactoryPropertySource {
1053 /// A property path through a named type in the factory's module.
1054 TypedProperty {
1055 /// Named receiver type in the producer module.
1056 type_name: String,
1057 /// Remaining path through the receiver type.
1058 property_path: String,
1059 },
1060 /// A synchronous function call in the factory's module.
1061 FunctionReturn {
1062 /// Function binding in the producer module.
1063 callee_name: String,
1064 },
1065 /// A proven instance-returning static class method.
1066 StaticFactoryReturn {
1067 /// Class binding in the producer module.
1068 callee_object: String,
1069 /// Statically named instance-returning method.
1070 callee_method: String,
1071 },
1072 /// A class proven in the object factory's own module.
1073 LocalClass {
1074 /// Local class binding resolved relative to the factory module.
1075 class_local_name: String,
1076 },
1077 /// Return of the callback at this ordinal in the proven helper declaration.
1078 CallbackParameterReturn {
1079 /// Zero-based formal parameter ordinal.
1080 parameter_index: u32,
1081 },
1082}
1083
1084/// Callback-origin member use, joined with the callee module's property source.
1085#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1086#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1087pub struct CallbackFactoryPropertyAccessFact {
1088 /// Callee import binding in the caller module.
1089 pub callee_name: String,
1090 /// Static export selected from a namespace import, if present.
1091 pub callee_member: Option<String>,
1092 /// Requested path in the wrapper's returned value.
1093 pub property_path: String,
1094 /// Requested member on the callback result.
1095 pub member: String,
1096 /// A property write permits only the canonical Vue getter contract.
1097 pub vue_only: bool,
1098 /// Ordinary assigned value, ignored by a canonical Vue setter contract.
1099 pub assigned_class: Option<String>,
1100 /// Callback ordinal and class origin interpreted in the caller module.
1101 pub arguments: Vec<CallbackFactoryArgument>,
1102}
1103
1104/// Proven callback result owned by a factory consumer's module.
1105#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1106#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1107pub struct CallbackFactoryArgument {
1108 /// Zero-based actual argument ordinal.
1109 pub parameter_index: u32,
1110 /// Class binding resolved in the consumer module.
1111 pub class_local_name: String,
1112 /// This argument is an options object with a proven `get` callback.
1113 pub getter: bool,
1114 /// No mutable capture makes a lazy invocation select another class.
1115 pub lazy_safe: bool,
1116}
1117
1118/// An exported object factory's deferred property receiver.
1119#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1120#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1121pub struct FactoryReturnObjectPropertySourceFact {
1122 /// Public factory export name.
1123 pub factory_export_name: String,
1124 /// Path within the returned object, separate from any source property path.
1125 pub property_path: String,
1126 /// Names interpreted relative to this fact's owning module.
1127 pub source: FactoryPropertySource,
1128}
1129
1130/// The load kind of the dynamic imports or patterns that start at `span_start`.
1131#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1132#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1133pub struct ImportLoadKindOverrideFact {
1134 /// Byte offset of the call or `new` expression that records the edge.
1135 pub span_start: u32,
1136 /// The load kind of every edge that the expression records.
1137 pub kind: ImportLoadKind,
1138}
1139
1140/// The Module Federation runtime function that a call names.
1141#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1142#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1143#[serde(rename_all = "camelCase")]
1144pub enum FederationRuntimeCall {
1145 /// `registerRemotes([{ name, entry }])`.
1146 RegisterRemotes,
1147 /// `loadRemote('remote/module')`.
1148 LoadRemote,
1149 /// `init({ remotes: [{ name, entry }] })`.
1150 /// Appended because bitcode encodes enum variants by ordinal.
1151 Init,
1152 /// `createInstance({ remotes: [{ name, entry }] })`.
1153 CreateInstance,
1154}
1155
1156impl FederationRuntimeCall {
1157 /// The function name as the source writes it.
1158 #[must_use]
1159 pub const fn name(self) -> &'static str {
1160 match self {
1161 Self::RegisterRemotes => "registerRemotes",
1162 Self::LoadRemote => "loadRemote",
1163 Self::Init => "init",
1164 Self::CreateInstance => "createInstance",
1165 }
1166 }
1167}
1168
1169/// One remote that a Module Federation runtime call names.
1170///
1171/// `remote` is the remote alias when the argument is a static literal, and
1172/// `None` when the call receives a value that static analysis cannot read.
1173#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1174#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1175pub struct FederationRuntimeRemoteFact {
1176 /// The runtime function the call names.
1177 pub call: FederationRuntimeCall,
1178 /// The remote alias the call names, or `None` for a non-literal argument.
1179 pub remote: Option<String>,
1180}
1181
1182#[path = "extract_semantic_view.rs"]
1183mod semantic_view;
1184pub use semantic_view::*;
1185
1186#[path = "extract_member_facts.rs"]
1187mod member_facts;
1188pub use member_facts::*;
1189
1190#[path = "extract_components.rs"]
1191mod components;
1192pub use components::*;
1193
1194#[expect(
1195 clippy::trivially_copy_pass_by_ref,
1196 reason = "serde serialize_with requires &T"
1197)]
1198fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
1199 use serde::ser::SerializeMap;
1200 let mut map = serializer.serialize_map(Some(2))?;
1201 map.serialize_entry("start", &span.start)?;
1202 map.serialize_entry("end", &span.end)?;
1203 map.end()
1204}
1205
1206/// Export identifier.
1207#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1208pub enum ExportName {
1209 /// A named export (e.g., `export const foo`).
1210 Named(String),
1211 /// The default export.
1212 Default,
1213}
1214
1215impl ExportName {
1216 /// Compare against a string without allocating (avoids `to_string()`).
1217 #[must_use]
1218 pub fn matches_str(&self, s: &str) -> bool {
1219 match self {
1220 Self::Named(n) => n == s,
1221 Self::Default => s == "default",
1222 }
1223 }
1224}
1225
1226impl std::fmt::Display for ExportName {
1227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1228 match self {
1229 Self::Named(n) => write!(f, "{n}"),
1230 Self::Default => write!(f, "default"),
1231 }
1232 }
1233}
1234
1235/// An import declaration.
1236#[derive(Debug, Clone)]
1237pub struct ImportInfo {
1238 /// The import specifier (e.g., `./utils` or `react`).
1239 pub source: String,
1240 /// How the symbol is imported (named, default, namespace, or side-effect).
1241 pub imported_name: ImportedName,
1242 /// The local binding name in the importing module.
1243 pub local_name: String,
1244 /// Whether this is a type-only import (`import type`).
1245 pub is_type_only: bool,
1246 /// Whether this whole-module import forwards type meanings only.
1247 ///
1248 /// Set for `export type *` and `export type * as ns` inside a
1249 /// `declare module '...'` body (issue #2375). Those forms record the same
1250 /// bindingless whole-module shape the plain ambient star records
1251 /// (issue #2357), but the star they stand for erases every value meaning,
1252 /// so the graph credits the target's star surface in the type namespace
1253 /// alone. Every other import leaves this false: `is_type_only` already
1254 /// decides their namespace on its own.
1255 pub is_type_only_star: bool,
1256 /// Whether this import originated from a CSS-context.
1257 pub from_style: bool,
1258 /// Source span of the import declaration.
1259 pub span: Span,
1260 /// Span of the source string literal used by the LSP to highlight the specifier.
1261 pub source_span: Span,
1262}
1263
1264/// How a symbol is imported.
1265#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1266pub enum ImportedName {
1267 /// A named import (e.g., `import { foo }`).
1268 Named(String),
1269 /// A default import (e.g., `import React`).
1270 Default,
1271 /// A namespace import (e.g., `import * as utils`).
1272 Namespace,
1273 /// A side-effect import (e.g., `import './styles.css'`).
1274 SideEffect,
1275}
1276
1277#[cfg(target_pointer_width = "64")]
1278const _: () = assert!(std::mem::size_of::<ExportInfo>() == 152);
1279#[cfg(target_pointer_width = "64")]
1280const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
1281#[cfg(target_pointer_width = "64")]
1282const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
1283#[cfg(target_pointer_width = "64")]
1284const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
1285#[cfg(target_pointer_width = "64")]
1286const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
1287#[cfg(target_pointer_width = "64")]
1288const _: () = assert!(std::mem::size_of::<SemanticFact>() == 80);
1289#[cfg(target_pointer_width = "64")]
1290const _: () = assert!(std::mem::size_of::<SinkSite>() == 224);
1291#[cfg(target_pointer_width = "64")]
1292const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 1624);
1293#[cfg(target_pointer_width = "64")]
1294const _: () = assert!(std::mem::size_of::<ImportBindingReference>() == 64);
1295#[cfg(target_pointer_width = "64")]
1296const _: () = assert!(std::mem::size_of::<TypeMemberTypeEntry>() == 72);
1297
1298#[path = "extract_re_export.rs"]
1299mod re_export;
1300pub use re_export::ReExportInfo;
1301
1302#[path = "extract_dynamic_pattern.rs"]
1303mod dynamic_pattern;
1304pub use dynamic_pattern::DynamicImportPattern;
1305
1306#[path = "extract_dynamic_import.rs"]
1307mod dynamic_import;
1308pub use dynamic_import::DynamicImportInfo;
1309
1310/// A `require()` call.
1311#[derive(Debug, Clone)]
1312pub struct RequireCallInfo {
1313 /// The require specifier.
1314 pub source: String,
1315 /// Source span of the `require()` call.
1316 pub span: Span,
1317 /// Span of the string-literal argument with quotes (`'./x'`), which anchors an
1318 /// `unresolved-import` diagnostic. `Span::default()` for a non-literal argument.
1319 pub source_span: Span,
1320 /// Names destructured from the `require()` result.
1321 pub destructured_names: Vec<String>,
1322 /// The `(key, local)` pair of each destructured identifier property:
1323 /// `const { exec: run } = require(...)` gives `("exec", "run")`.
1324 pub destructured_locals: Vec<(String, String)>,
1325 /// The local variable name for `const x = require(...)`.
1326 pub local_name: Option<String>,
1327 /// `true` for `import type X = require('...')`, the one require spelling
1328 /// TypeScript erases entirely: the emitted JavaScript contains no
1329 /// `require` call, so the target is a type-space reference and never a
1330 /// runtime dependency. Always `false` for `const x = require(...)`, which
1331 /// has no type-only spelling. Read by dependency classification so a
1332 /// type-only devDependency is not reported as production usage.
1333 pub is_type_only: bool,
1334}
1335
1336/// Result of parsing all files, including incremental cache statistics.
1337pub struct ParseResult {
1338 /// Extracted module information for all successfully parsed files.
1339 pub modules: Vec<ModuleInfo>,
1340 /// Files discovered with stable IDs but unreadable by the parser.
1341 pub read_failures: Vec<SourceReadFailure>,
1342 /// Files whose extracted modules may be incomplete because of parse diagnostics.
1343 /// Analysis keeps findings visible and attaches caveats to affected findings.
1344 pub parse_degradations: Vec<SourceParseDegradation>,
1345 /// Number of files whose parse results were loaded from cache (unchanged).
1346 pub cache_hits: usize,
1347 /// Number of files that required a full parse (new or changed).
1348 pub cache_misses: usize,
1349 /// Summed wall-clock time of the actual AST parses across all rayon workers.
1350 pub parse_cpu_ms: f64,
1351 /// Files whose bytes were read from disk: every parse, plus every cache
1352 /// hit that had to compare the content hash.
1353 pub files_read: u64,
1354 /// Bytes of source read from disk across all files.
1355 pub source_bytes_read: u64,
1356 /// Source bytes that the CSS comment mask read across all parsed files.
1357 pub css_masked_bytes: u64,
1358 /// Files that the cache served from their metadata alone, without a read
1359 /// of the source, sorted by id. The stored fingerprint of each equals the
1360 /// metadata that the parse read, so a cache writer can keep it.
1361 pub metadata_hits: Vec<FileId>,
1362}
1363
1364/// A discovered source that could not be read as UTF-8 text.
1365#[derive(Debug, Clone, PartialEq, Eq)]
1366pub struct SourceReadFailure {
1367 /// Stable discovery identity retained even though no module was produced.
1368 pub file_id: FileId,
1369 /// Absolute discovered source path.
1370 pub path: PathBuf,
1371 /// Underlying filesystem or UTF-8 decoding error.
1372 pub error: String,
1373}
1374
1375/// A discovered source that was read but did not parse cleanly.
1376///
1377/// The module it produced is still analyzed: dropping it would turn one broken
1378/// file into project-wide silence. The point of carrying the degradation is
1379/// that the imports the file failed to parse credited nothing, so its targets
1380/// can be reported as unused with full confidence unless a consumer is told the
1381/// parse was partial.
1382#[derive(Debug, Clone, PartialEq, Eq)]
1383pub struct SourceParseDegradation {
1384 /// Stable discovery identity of the degraded source.
1385 pub file_id: FileId,
1386 /// Absolute discovered source path.
1387 pub path: PathBuf,
1388 /// Number of parser diagnostics reported for the file.
1389 pub error_count: u32,
1390 /// `true` when the parser abandoned the file instead of recovering.
1391 pub panicked: bool,
1392 /// The nesting cap when the file nests too deep to parse.
1393 pub nesting_limit: Option<u32>,
1394}
1395
1396#[path = "extract_effect.rs"]
1397mod effect;
1398pub use effect::*;
1399#[path = "extract_calls.rs"]
1400mod calls;
1401pub use calls::*;
1402#[path = "extract_function_contracts.rs"]
1403mod function_contracts;
1404pub use function_contracts::*;
1405#[path = "extract_factory.rs"]
1406mod factory;
1407pub use factory::*;
1408#[path = "extract_component_contracts.rs"]
1409mod component_contracts;
1410pub use component_contracts::*;
1411#[path = "extract_type_members.rs"]
1412mod type_members;
1413pub use type_members::*;
1414
1415#[path = "extract_template_members.rs"]
1416mod extract_template_members;
1417use extract_template_members::angular_template_member_names_from_parts;
1418
1419#[cfg(test)]
1420#[path = "extract_tests.rs"]
1421mod tests;