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