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/// One resolved property of an object-literal factory return: a dotted property
1925/// path mapped to the class the value at that path is an instance of.
1926///
1927/// `return { invoke: { orders: factory.ordersPage } }` records
1928/// `{ property_path: "invoke.orders", class_local_name: "OrdersPage" }`. The class
1929/// name is the factory module's own LOCAL name, resolved at analyze time through the
1930/// factory module's imports to the real class export. See issue #1858.
1931#[derive(
1932 Debug,
1933 Clone,
1934 serde::Serialize,
1935 serde::Deserialize,
1936 bitcode::Encode,
1937 bitcode::Decode,
1938 PartialEq,
1939 Eq,
1940)]
1941pub struct FactoryReturnObjectProperty {
1942 /// Dotted property path from the returned object literal (`orders`, `invoke.orders`).
1943 pub property_path: String,
1944 /// The property value's class local name within the factory module.
1945 pub class_local_name: String,
1946}
1947
1948/// An exported factory function that returns an object literal whose property
1949/// values are class instances, joined to its public export name.
1950///
1951/// A cross-module `const ui = createUi(); ui.orders.member` consumer emits a
1952/// `FactoryReturnObjectPropertyAccess` fact; the analyze layer resolves `export_name`
1953/// through the consumer's imports to this module, matches `property_path`, and credits
1954/// `member` on the resolved class (gated on it being a class with members). See issue #1858.
1955#[derive(
1956 Debug,
1957 Clone,
1958 serde::Serialize,
1959 serde::Deserialize,
1960 bitcode::Encode,
1961 bitcode::Decode,
1962 PartialEq,
1963 Eq,
1964)]
1965pub struct FactoryReturnObjectShapeExport {
1966 /// Public export name (honors `export { createUi as createOrdersUi }`).
1967 pub export_name: String,
1968 /// Resolved `(property_path -> class_local_name)` entries for the returned literal.
1969 pub properties: Box<[FactoryReturnObjectProperty]>,
1970}
1971
1972/// A named-type property whose declared type is a named type reference.
1973///
1974/// `interface Opts { c: OptDep }` (or `type Opts = { c: OptDep }`) records
1975/// `TypeMemberTypeEntry { type_name: "Opts", property: "c", property_type: "OptDep" }`.
1976/// Both `type_name` and `property_type` are the DECLARING module's own local
1977/// names; resolution through that module's imports/exports is deferred to
1978/// analyze time, mirroring `FactoryReturnExport.class_local_name`. Consumed by
1979/// the `unused-class-member` typed-property-hop join so a consumer's
1980/// `this.opts.c.optM()` credits `OptDep.optM` across module boundaries.
1981/// See issue #1785.
1982#[derive(
1983 Debug,
1984 Clone,
1985 serde::Serialize,
1986 serde::Deserialize,
1987 bitcode::Encode,
1988 bitcode::Decode,
1989 PartialEq,
1990 Eq,
1991)]
1992pub struct TypeMemberTypeEntry {
1993 /// Local interface or type-alias name declaring the property.
1994 pub type_name: String,
1995 /// Property name declared on the type.
1996 pub property: String,
1997 /// The property's declared type name (local to the declaring module).
1998 pub property_type: String,
1999}
2000
2001/// A module-scope declaration that can be used as a TypeScript type.
2002#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
2003pub struct LocalTypeDeclaration {
2004 /// Local declaration name.
2005 pub name: String,
2006 /// Declaration identifier span.
2007 #[serde(serialize_with = "serialize_span")]
2008 pub span: Span,
2009}
2010
2011/// A reference from an exported symbol's public signature to a type name.
2012#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
2013pub struct PublicSignatureTypeReference {
2014 /// Exported symbol whose signature contains the reference.
2015 pub export_name: String,
2016 /// Referenced type name. Qualified names are reduced to their root identifier.
2017 pub type_name: String,
2018 /// Reference span.
2019 #[serde(serialize_with = "serialize_span")]
2020 pub span: Span,
2021 /// True when the reference comes from a `satisfies` clause. The clause
2022 /// checks the value but does not change the exported type, so the type is
2023 /// in use but is not a private type leak.
2024 #[serde(skip_serializing_if = "std::ops::Not::not")]
2025 pub from_satisfies: bool,
2026}
2027
2028/// A member of an enum, class, or namespace.
2029#[derive(Debug, Clone, serde::Serialize)]
2030pub struct MemberInfo {
2031 /// Member name.
2032 pub name: String,
2033 /// The kind of member (enum, class method/property, or namespace member).
2034 pub kind: MemberKind,
2035 /// Source span of the member declaration.
2036 #[serde(serialize_with = "serialize_span")]
2037 pub span: Span,
2038 /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
2039 /// Decorated members are used by frameworks at runtime and should not be
2040 /// flagged as unused class members, unless every decorator on the member
2041 /// is opted out via `FallowConfig.ignore_decorators`.
2042 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2043 pub has_decorator: bool,
2044 /// Full dotted path of each decorator on this member, in source order.
2045 /// `@step("x")` stores `"step"`; `@ns.foo` stores `"ns.foo"`. Empty for
2046 /// undecorated members, Angular signal-initializer properties (which set
2047 /// `has_decorator` without a literal decorator AST node), and decorators
2048 /// whose expression is not an identifier ladder (the entry is the empty
2049 /// string in that case, treated as never-matching by the predicate).
2050 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2051 pub decorator_names: Vec<String>,
2052 /// True when this is a static class method that returns a fresh instance
2053 /// of the same class: either via `return new this()` / `return new
2054 /// <SameClassName>()` in the body's last statement, or via a declared
2055 /// return type matching the class name. Consumers calling such a static
2056 /// method receive an instance, so the call result's member accesses are
2057 /// credited against the class. See issues #346, #387.
2058 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2059 pub is_instance_returning_static: bool,
2060 /// True when this is an instance class method whose call result is an
2061 /// instance of the same class. Qualifies when the declared return type
2062 /// matches the class name (`setX(): EventBuilder { ... }`) or when the
2063 /// body's last statement is `return this`. The analyze layer walks fluent
2064 /// chains (`Class.factory().setX().setY()`) only through methods carrying
2065 /// this flag, so the chain stops at a non-self-returning method like
2066 /// `.build()`. See issue #387.
2067 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2068 pub is_self_returning: bool,
2069 /// Root identifier of the class `extends` expression, set only when the
2070 /// member has the `override` modifier: `Container` in
2071 /// `extends Container<Env>`, `Schema` in `extends Schema.TaggedError<E>()(...)`.
2072 /// The analysis credits the member when this root names code outside the
2073 /// project, because that code calls the overridden member.
2074 #[serde(default, skip_serializing_if = "Option::is_none")]
2075 pub override_base: Option<String>,
2076}
2077
2078/// The kind of member.
2079#[derive(
2080 Debug,
2081 Clone,
2082 Copy,
2083 PartialEq,
2084 Eq,
2085 serde::Serialize,
2086 serde::Deserialize,
2087 bitcode::Encode,
2088 bitcode::Decode,
2089)]
2090#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2091#[serde(rename_all = "snake_case")]
2092pub enum MemberKind {
2093 /// A TypeScript enum member.
2094 EnumMember,
2095 /// A class method.
2096 ClassMethod,
2097 /// A class property.
2098 ClassProperty,
2099 /// A member exported from a TypeScript namespace.
2100 NamespaceMember,
2101 /// A member declared by a store object (Pinia `state` / `getters` /
2102 /// `actions` key, or a setup-store returned key). Cross-graph dead-member
2103 /// detection: a store member never accessed by any consumer project-wide.
2104 StoreMember,
2105}
2106
2107/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
2108#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
2109pub struct MemberAccess {
2110 /// The identifier being accessed (the import name).
2111 pub object: String,
2112 /// The member being accessed.
2113 pub member: String,
2114}
2115
2116/// Direct export declarations that TypeScript treats as one merged symbol.
2117///
2118/// Spans identify the exact declaration slots without conflating unrelated
2119/// type/value declarations that happen to share a name.
2120#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2121#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2122pub struct DeclarationMergeFact {
2123 /// Identifier spans for the declarations in this merge group.
2124 pub export_spans: Vec<(u32, u32)>,
2125}
2126
2127/// A default import binding consumed outside a statically known member access.
2128///
2129/// Resolution decides whether the target is an object-shaped module such as a
2130/// CSS Module or a proven static CommonJS object map. Keeping this fact
2131/// target-agnostic lets aliases and extensionless specifiers use the resolved
2132/// target path without broadening ordinary default-import behavior.
2133#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2134#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2135pub struct DefaultImportWholeObjectUseFact {
2136 /// Local binding name in the importing module.
2137 pub local_name: String,
2138}
2139
2140/// A typed extraction fact for cross-layer analysis.
2141#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2142#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2143#[serde(tag = "kind", rename_all = "snake_case")]
2144pub enum SemanticFact {
2145 /// A class member referenced from an Angular template, host binding, or
2146 /// component metadata entry.
2147 AngularTemplateMemberAccess(AngularTemplateMemberAccessFact),
2148 /// An Angular component field whose value is an array of a class.
2149 AngularComponentFieldArrayType(AngularComponentFieldArrayTypeFact),
2150 /// An Angular component spreads `this` into an object literal, so component
2151 /// input/output usage is opaque.
2152 AngularThisSpread(AngularThisSpreadFact),
2153 /// A member access on a value returned by an imported static factory call.
2154 FactoryCallMemberAccess(FactoryCallMemberAccessFact),
2155 /// A member access on a value returned by an imported free-function factory
2156 /// (`const x = importedFactory(); x.member`). See issue #1441 (Part A).
2157 FactoryFnMemberAccess(FactoryFnMemberAccessFact),
2158 /// A member access reached through a property of a value whose declared
2159 /// type is an imported named type (`this.opts.c.optM()` where `opts` is
2160 /// typed by an imported interface). See issue #1785.
2161 TypedPropertyMemberAccess(TypedPropertyMemberAccessFact),
2162 /// A member access on a fluent chain rooted at an imported static factory.
2163 FluentChainMemberAccess(FluentChainMemberAccessFact),
2164 /// A member access on a fluent chain rooted at a `new` expression.
2165 FluentChainNewMemberAccess(FluentChainNewMemberAccessFact),
2166 /// A member access on a Playwright fixture object inside a test callback.
2167 PlaywrightFixtureUse(PlaywrightFixtureUseFact),
2168 /// A Playwright fixture definition declared by a typed `test.extend<T>()`.
2169 PlaywrightFixtureDefinition(PlaywrightFixtureDefinitionFact),
2170 /// A Playwright fixture wrapper alias declared by `mergeTests` or `.extend`.
2171 PlaywrightFixtureAlias(PlaywrightFixtureAliasFact),
2172 /// A nested Playwright fixture binding declared by a fixture type alias.
2173 PlaywrightFixtureType(PlaywrightFixtureTypeFact),
2174 /// An exported value whose runtime instance targets a local class or interface.
2175 InstanceExportBinding(InstanceExportBindingFact),
2176 /// A dynamic custom-element tag render that makes static Lit tag credit opaque.
2177 DynamicCustomElementRender(DynamicCustomElementRenderFact),
2178 /// A factory-returned value consumed in a way that can expose ANY property
2179 /// (`const { a, ...rest } = importedFactory()`, a computed destructure key).
2180 /// The returned class must be treated as wholly used: crediting only the
2181 /// visible keys would leave a live member reported as dead.
2182 ///
2183 /// Appended, never inserted: `bitcode` encodes an enum by ordinal, so moving an
2184 /// existing variant would make an old cache decode one fact as another.
2185 FactoryFnWholeObject(FactoryFnWholeObjectFact),
2186 /// A member access reached through a property of a value returned by an
2187 /// imported factory that returns an object literal (`const ui = createUi();
2188 /// ui.orders.member`). Appended after `FactoryFnWholeObject`, never inserted
2189 /// (bitcode encodes by ordinal). See issue #1858.
2190 FactoryReturnObjectPropertyAccess(FactoryReturnObjectPropertyAccessFact),
2191 /// A `this.<field>.<member>` access tied to its exact enclosing class.
2192 /// Appended because bitcode encodes enum variants by ordinal.
2193 ClassThisMemberAccess(ClassThisMemberAccessFact),
2194 /// A whole-object use of `this.<field>...` tied to its exact enclosing class.
2195 /// Appended because bitcode encodes enum variants by ordinal.
2196 ClassThisWholeObjectUse(ClassThisWholeObjectUseFact),
2197 /// An ordered Vitest module-mock operation with direct imported-`vi`
2198 /// provenance.
2199 ///
2200 /// Appended because bitcode encodes enum variants by ordinal. The ordinary
2201 /// dynamic-import fact for the same source remains authoritative for graph
2202 /// reachability and unresolved-import diagnostics.
2203 VitestModuleMockOperation(VitestModuleMockOperationFact),
2204 /// Direct declarations that form one legal TypeScript declaration merge.
2205 /// Appended because bitcode encodes enum variants by ordinal.
2206 DeclarationMerge(DeclarationMergeFact),
2207 /// A named type whose direct receiver surface is contributed by another
2208 /// named type (for example `Pick<Base, ...>` or a union constituent).
2209 /// Appended because bitcode encodes enum variants by ordinal.
2210 TypeAliasSurfaceTarget(TypeAliasSurfaceTargetFact),
2211 /// A string-valued TypeScript enum member available as a static property key.
2212 /// Appended because bitcode encodes enum variants by ordinal.
2213 StringEnumMemberValue(StringEnumMemberValueFact),
2214 /// A computed property access keyed by a static enum member.
2215 /// Appended because bitcode encodes enum variants by ordinal.
2216 ComputedEnumKeyUse(ComputedEnumKeyUseFact),
2217 /// A directly declared non-optional member required by a named interface
2218 /// or object type.
2219 /// Appended because bitcode encodes enum variants by ordinal.
2220 RequiredTypeMember(RequiredTypeMemberFact),
2221 /// The file's complete CommonJS assignment surface is exactly one
2222 /// top-level `module.exports = { ... }` object literal whose keys are all
2223 /// static and which has no transpilation marker or competing assignment.
2224 /// Appended because bitcode encodes enum variants by ordinal.
2225 CjsSingleStaticObjectMap,
2226 /// A default import binding was handed on as a whole object.
2227 /// Appended because bitcode encodes enum variants by ordinal.
2228 DefaultImportWholeObjectUse(DefaultImportWholeObjectUseFact),
2229 /// A property of an exported object contains a local class instance.
2230 /// Appended because bitcode encodes enum variants by ordinal.
2231 ExportedObjectInstanceProperty(ExportedObjectInstancePropertyFact),
2232 /// A proven class member read selected through a namespace import.
2233 /// Appended because bitcode encodes enum variants by ordinal.
2234 QualifiedClassMemberAccess(QualifiedClassMemberAccessFact),
2235 /// A Module Federation runtime call (`registerRemotes`, `loadRemote`,
2236 /// `init` or `createInstance`) imported from a Federation runtime package.
2237 /// Appended because bitcode encodes enum variants by ordinal.
2238 FederationRuntimeRemote(FederationRuntimeRemoteFact),
2239 /// A dynamic import or an import pattern whose load kind differs from the
2240 /// default of its list: `Dynamic` for `dynamic_imports` and
2241 /// `DynamicPattern` for `dynamic_import_patterns`.
2242 /// Appended because bitcode encodes enum variants by ordinal.
2243 ImportLoadKindOverride(ImportLoadKindOverrideFact),
2244 /// A source-owned class-producing property of an exported object factory.
2245 /// Appended because bitcode encodes enum variants by ordinal.
2246 FactoryReturnObjectPropertySource(Box<FactoryReturnObjectPropertySourceFact>),
2247 /// Property read whose bound factory receiver passed source-time lexical and value checks.
2248 ProvenFactoryReturnObjectPropertyAccess(FactoryReturnObjectPropertyAccessFact),
2249 /// Caller-owned callback origins for a source-proven returned property.
2250 CallbackFactoryPropertyAccess(Box<CallbackFactoryPropertyAccessFact>),
2251 /// A Playwright fixture definition from `<base>.extend<T>()` where `base`
2252 /// is imported. Analysis applies it only when `base` resolves to a
2253 /// Playwright test. Appended because bitcode encodes enum variants by ordinal.
2254 PlaywrightConditionalFixtureDefinition(Box<PlaywrightConditionalFixtureDefinitionFact>),
2255 /// A local name that the extractor proved holds a Playwright test.
2256 /// Appended because bitcode encodes enum variants by ordinal.
2257 PlaywrightTestBinding(PlaywrightTestBindingFact),
2258 /// A top-level statement or declaration emits runtime code beyond module
2259 /// imports and exports, which have their own extraction records.
2260 /// Appended because bitcode encodes enum variants by ordinal.
2261 TopLevelRuntimeStatement,
2262 /// A static member name probed with `"name" in value` or `Reflect.has(value, "name")`.
2263 /// Appended because bitcode encodes enum variants by ordinal.
2264 MemberNameProbe(MemberNameProbeFact),
2265 /// A use of a member of a TypeScript namespace that a plain member access
2266 /// does not record: a nested chain (`N.Inner.x`), a value that leaves the
2267 /// chain (`use(N)`), or a reference inside the namespace body.
2268 /// Appended because bitcode encodes enum variants by ordinal.
2269 NamespaceMemberUse(NamespaceMemberUseFact),
2270}
2271
2272/// A use of a namespace member, found by the semantic pass.
2273#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2274#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2275pub struct NamespaceMemberUseFact {
2276 /// The local name of the root binding: an import binding, or a namespace
2277 /// that the module declares, or the key of an inline import type.
2278 pub object: String,
2279 /// The dotted member path after the root. Empty for a bare root.
2280 pub path: String,
2281 /// The code hands the value at `path` on (an argument, an alias, a
2282 /// spread). Every member below `path` then counts as used.
2283 pub whole: bool,
2284}
2285
2286/// A static member name that a runtime probe checks on an untyped value.
2287#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2288#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2289pub struct MemberNameProbeFact {
2290 /// The probed member name.
2291 pub name: String,
2292}
2293
2294/// Deferred class provenance owned by the module declaring an object factory.
2295#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2296#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2297pub enum FactoryPropertySource {
2298 /// A property path through a named type in the factory's module.
2299 TypedProperty {
2300 /// Named receiver type in the producer module.
2301 type_name: String,
2302 /// Remaining path through the receiver type.
2303 property_path: String,
2304 },
2305 /// A synchronous function call in the factory's module.
2306 FunctionReturn {
2307 /// Function binding in the producer module.
2308 callee_name: String,
2309 },
2310 /// A proven instance-returning static class method.
2311 StaticFactoryReturn {
2312 /// Class binding in the producer module.
2313 callee_object: String,
2314 /// Statically named instance-returning method.
2315 callee_method: String,
2316 },
2317 /// A class proven in the object factory's own module.
2318 LocalClass {
2319 /// Local class binding resolved relative to the factory module.
2320 class_local_name: String,
2321 },
2322 /// Return of the callback at this ordinal in the proven helper declaration.
2323 CallbackParameterReturn {
2324 /// Zero-based formal parameter ordinal.
2325 parameter_index: u32,
2326 },
2327}
2328
2329/// Callback-origin member use, joined with the callee module's property source.
2330#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2331#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2332pub struct CallbackFactoryPropertyAccessFact {
2333 /// Callee import binding in the caller module.
2334 pub callee_name: String,
2335 /// Static export selected from a namespace import, if present.
2336 pub callee_member: Option<String>,
2337 /// Requested path in the wrapper's returned value.
2338 pub property_path: String,
2339 /// Requested member on the callback result.
2340 pub member: String,
2341 /// A property write permits only the canonical Vue getter contract.
2342 pub vue_only: bool,
2343 /// Ordinary assigned value, ignored by a canonical Vue setter contract.
2344 pub assigned_class: Option<String>,
2345 /// Callback ordinal and class origin interpreted in the caller module.
2346 pub arguments: Vec<CallbackFactoryArgument>,
2347}
2348
2349/// Proven callback result owned by a factory consumer's module.
2350#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2351#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2352pub struct CallbackFactoryArgument {
2353 /// Zero-based actual argument ordinal.
2354 pub parameter_index: u32,
2355 /// Class binding resolved in the consumer module.
2356 pub class_local_name: String,
2357 /// This argument is an options object with a proven `get` callback.
2358 pub getter: bool,
2359 /// No mutable capture makes a lazy invocation select another class.
2360 pub lazy_safe: bool,
2361}
2362
2363/// An exported object factory's deferred property receiver.
2364#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2365#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2366pub struct FactoryReturnObjectPropertySourceFact {
2367 /// Public factory export name.
2368 pub factory_export_name: String,
2369 /// Path within the returned object, separate from any source property path.
2370 pub property_path: String,
2371 /// Names interpreted relative to this fact's owning module.
2372 pub source: FactoryPropertySource,
2373}
2374
2375/// The load kind of the dynamic imports or patterns that start at `span_start`.
2376#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2377#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2378pub struct ImportLoadKindOverrideFact {
2379 /// Byte offset of the call or `new` expression that records the edge.
2380 pub span_start: u32,
2381 /// The load kind of every edge that the expression records.
2382 pub kind: ImportLoadKind,
2383}
2384
2385/// The Module Federation runtime function that a call names.
2386#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2387#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2388#[serde(rename_all = "camelCase")]
2389pub enum FederationRuntimeCall {
2390 /// `registerRemotes([{ name, entry }])`.
2391 RegisterRemotes,
2392 /// `loadRemote('remote/module')`.
2393 LoadRemote,
2394 /// `init({ remotes: [{ name, entry }] })`.
2395 /// Appended because bitcode encodes enum variants by ordinal.
2396 Init,
2397 /// `createInstance({ remotes: [{ name, entry }] })`.
2398 CreateInstance,
2399}
2400
2401impl FederationRuntimeCall {
2402 /// The function name as the source writes it.
2403 #[must_use]
2404 pub const fn name(self) -> &'static str {
2405 match self {
2406 Self::RegisterRemotes => "registerRemotes",
2407 Self::LoadRemote => "loadRemote",
2408 Self::Init => "init",
2409 Self::CreateInstance => "createInstance",
2410 }
2411 }
2412}
2413
2414/// One remote that a Module Federation runtime call names.
2415///
2416/// `remote` is the remote alias when the argument is a static literal, and
2417/// `None` when the call receives a value that static analysis cannot read.
2418#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2419#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2420pub struct FederationRuntimeRemoteFact {
2421 /// The runtime function the call names.
2422 pub call: FederationRuntimeCall,
2423 /// The remote alias the call names, or `None` for a non-literal argument.
2424 pub remote: Option<String>,
2425}
2426
2427/// Iterate Angular template member names from typed semantic facts.
2428fn angular_template_member_names_from_parts(
2429 semantic_facts: &[SemanticFact],
2430) -> impl Iterator<Item = &str> {
2431 semantic_facts.iter().filter_map(|fact| {
2432 if let SemanticFact::AngularTemplateMemberAccess(access) = fact {
2433 Some(access.member.as_str())
2434 } else {
2435 None
2436 }
2437 })
2438}
2439
2440/// Iterate Angular template member names from a module's typed facts.
2441pub fn angular_template_member_names(module: &ModuleInfo) -> impl Iterator<Item = &str> {
2442 angular_template_member_names_from_parts(&module.semantic_facts)
2443}
2444
2445/// Return true when the fact slice contains any Angular template member
2446/// reference.
2447#[must_use]
2448fn has_angular_template_members_from_parts(semantic_facts: &[SemanticFact]) -> bool {
2449 angular_template_member_names_from_parts(semantic_facts)
2450 .next()
2451 .is_some()
2452}
2453
2454/// Return true when the module contains any Angular template member reference.
2455#[must_use]
2456pub fn has_angular_template_members(module: &ModuleInfo) -> bool {
2457 has_angular_template_members_from_parts(&module.semantic_facts)
2458}
2459
2460/// Return true when a module spreads `this` in Angular template context.
2461#[must_use]
2462pub fn has_angular_this_spread(module: &ModuleInfo) -> bool {
2463 SemanticFactView::new(&module.semantic_facts, &module.member_accesses).has_angular_this_spread()
2464}
2465
2466/// Return true when a module contains a dynamic custom-element render.
2467#[must_use]
2468pub fn has_dynamic_custom_element_render(module: &ModuleInfo) -> bool {
2469 module
2470 .semantic_facts
2471 .iter()
2472 .any(|fact| matches!(fact, SemanticFact::DynamicCustomElementRender(_)))
2473}
2474
2475/// Typed-first view over semantic extraction facts.
2476///
2477/// Extraction populates `semantic_facts` directly. The `member_accesses` slice
2478/// remains available for consumers that need ordinary source member accesses,
2479/// but it is no longer decoded as a string protocol for semantic facts.
2480#[derive(Debug, Clone, Copy)]
2481pub struct SemanticFactView<'a> {
2482 semantic_facts: &'a [SemanticFact],
2483 member_accesses: &'a [MemberAccess],
2484}
2485
2486impl<'a> SemanticFactView<'a> {
2487 /// Create a typed semantic fact view from current semantic facts plus
2488 /// ordinary source member accesses.
2489 #[must_use]
2490 pub const fn new(
2491 semantic_facts: &'a [SemanticFact],
2492 member_accesses: &'a [MemberAccess],
2493 ) -> Self {
2494 Self {
2495 semantic_facts,
2496 member_accesses,
2497 }
2498 }
2499
2500 /// Iterate typed semantic facts.
2501 pub fn facts(self) -> impl Iterator<Item = &'a SemanticFact> + 'a {
2502 self.semantic_facts.iter()
2503 }
2504
2505 /// Iterate Angular template member references.
2506 pub fn angular_template_member_names(self) -> impl Iterator<Item = &'a str> + 'a {
2507 angular_template_member_names_from_parts(self.semantic_facts)
2508 }
2509
2510 /// Collect Angular component field array-type facts.
2511 pub fn angular_component_field_array_types(self) -> Vec<AngularComponentFieldArrayTypeFact> {
2512 angular_component_field_array_type_facts(self.semantic_facts)
2513 .cloned()
2514 .collect()
2515 }
2516
2517 /// Return true when any Angular template member reference exists.
2518 #[must_use]
2519 pub fn has_angular_template_members(self) -> bool {
2520 self.angular_template_member_names().next().is_some()
2521 }
2522
2523 /// Return true when a module spreads `this` in Angular template context.
2524 #[must_use]
2525 pub fn has_angular_this_spread(self) -> bool {
2526 self.semantic_facts
2527 .iter()
2528 .any(|fact| matches!(fact, SemanticFact::AngularThisSpread(_)))
2529 }
2530
2531 /// Iterate ordinary source member accesses.
2532 pub fn ordinary_member_accesses(self) -> impl Iterator<Item = &'a MemberAccess> + 'a {
2533 self.member_accesses.iter()
2534 }
2535
2536 /// Collect class-scoped `this` member-access facts.
2537 pub fn class_this_member_accesses(self) -> Vec<ClassThisMemberAccessFact> {
2538 class_this_member_access_facts(self.semantic_facts)
2539 .cloned()
2540 .collect()
2541 }
2542
2543 /// Collect class-scoped `this` whole-object-use facts.
2544 pub fn class_this_whole_object_uses(self) -> Vec<ClassThisWholeObjectUseFact> {
2545 class_this_whole_object_use_facts(self.semantic_facts)
2546 .cloned()
2547 .collect()
2548 }
2549
2550 /// Collect instance-export binding facts.
2551 pub fn instance_export_bindings(self) -> Vec<InstanceExportBindingFact> {
2552 instance_export_binding_facts(self.semantic_facts)
2553 .cloned()
2554 .collect()
2555 }
2556
2557 /// Iterate exported object properties that contain class instances.
2558 pub fn exported_object_instance_properties(
2559 self,
2560 ) -> impl Iterator<Item = &'a ExportedObjectInstancePropertyFact> + 'a {
2561 exported_object_instance_property_facts(self.semantic_facts)
2562 }
2563
2564 /// Iterate proven namespace-qualified class member accesses.
2565 pub fn qualified_class_member_accesses(
2566 self,
2567 ) -> impl Iterator<Item = &'a QualifiedClassMemberAccessFact> + 'a {
2568 qualified_class_member_access_facts(self.semantic_facts)
2569 }
2570
2571 /// Collect static factory call member facts.
2572 pub fn factory_call_member_accesses(self) -> Vec<FactoryCallMemberAccessFact> {
2573 factory_call_member_access_facts(self.semantic_facts)
2574 .cloned()
2575 .collect()
2576 }
2577
2578 /// Collect free-function factory-return member facts.
2579 pub fn factory_fn_member_accesses(self) -> Vec<FactoryFnMemberAccessFact> {
2580 factory_fn_member_access_facts(self.semantic_facts)
2581 .cloned()
2582 .collect()
2583 }
2584
2585 /// Collect factory-return whole-object consumption facts.
2586 pub fn factory_fn_whole_objects(self) -> Vec<FactoryFnWholeObjectFact> {
2587 factory_fn_whole_object_facts(self.semantic_facts)
2588 .cloned()
2589 .collect()
2590 }
2591
2592 /// Collect object-literal factory-return property member facts.
2593 pub fn factory_return_object_property_accesses(
2594 self,
2595 ) -> Vec<FactoryReturnObjectPropertyAccessFact> {
2596 factory_return_object_property_access_facts(self.semantic_facts)
2597 .cloned()
2598 .collect()
2599 }
2600
2601 /// Iterate deferred object-factory property sources without copying their names.
2602 pub fn factory_return_object_property_sources(
2603 self,
2604 ) -> impl Iterator<Item = &'a FactoryReturnObjectPropertySourceFact> + 'a {
2605 self.semantic_facts.iter().filter_map(|fact| match fact {
2606 SemanticFact::FactoryReturnObjectPropertySource(source) => Some(source.as_ref()),
2607 _ => None,
2608 })
2609 }
2610
2611 /// Property accesses with source-owned receiver admission.
2612 pub fn proven_factory_return_object_property_accesses(
2613 self,
2614 ) -> impl Iterator<Item = &'a FactoryReturnObjectPropertyAccessFact> + 'a {
2615 self.semantic_facts.iter().filter_map(|fact| match fact {
2616 SemanticFact::ProvenFactoryReturnObjectPropertyAccess(access) => Some(access),
2617 _ => None,
2618 })
2619 }
2620
2621 /// Iterate caller-owned callback property projections.
2622 pub fn callback_factory_property_accesses(
2623 self,
2624 ) -> impl Iterator<Item = &'a CallbackFactoryPropertyAccessFact> + 'a {
2625 self.semantic_facts.iter().filter_map(|fact| match fact {
2626 SemanticFact::CallbackFactoryPropertyAccess(access) => Some(access.as_ref()),
2627 _ => None,
2628 })
2629 }
2630
2631 /// Collect typed-property-hop member facts.
2632 pub fn typed_property_member_accesses(self) -> Vec<TypedPropertyMemberAccessFact> {
2633 typed_property_member_access_facts(self.semantic_facts)
2634 .cloned()
2635 .collect()
2636 }
2637
2638 /// Collect members whose presence is required by a named structural type.
2639 pub fn required_type_members(self) -> impl Iterator<Item = &'a RequiredTypeMemberFact> + 'a {
2640 required_type_member_facts(self.semantic_facts)
2641 }
2642
2643 /// Collect type-alias receiver-surface edges.
2644 pub fn type_alias_surface_targets(self) -> Vec<TypeAliasSurfaceTargetFact> {
2645 type_alias_surface_target_facts(self.semantic_facts)
2646 .cloned()
2647 .collect()
2648 }
2649
2650 /// Collect string-valued enum member definitions.
2651 pub fn string_enum_member_values(self) -> Vec<StringEnumMemberValueFact> {
2652 string_enum_member_value_facts(self.semantic_facts)
2653 .cloned()
2654 .collect()
2655 }
2656
2657 /// Collect computed property accesses keyed by enum members.
2658 pub fn computed_enum_key_uses(self) -> Vec<ComputedEnumKeyUseFact> {
2659 computed_enum_key_use_facts(self.semantic_facts)
2660 .cloned()
2661 .collect()
2662 }
2663
2664 /// Collect static factory fluent-chain member facts.
2665 pub fn fluent_chain_member_accesses(self) -> Vec<FluentChainMemberAccessFact> {
2666 fluent_chain_member_access_facts(self.semantic_facts)
2667 .cloned()
2668 .collect()
2669 }
2670
2671 /// Collect constructor-rooted fluent-chain member facts.
2672 pub fn fluent_chain_new_member_accesses(self) -> Vec<FluentChainNewMemberAccessFact> {
2673 fluent_chain_new_member_access_facts(self.semantic_facts)
2674 .cloned()
2675 .collect()
2676 }
2677
2678 /// Collect Playwright fixture-use facts.
2679 pub fn playwright_fixture_uses(self) -> Vec<PlaywrightFixtureUseFact> {
2680 playwright_fixture_use_facts(self.semantic_facts)
2681 .cloned()
2682 .collect()
2683 }
2684
2685 /// Collect Playwright fixture-definition facts.
2686 pub fn playwright_fixture_definitions(self) -> Vec<PlaywrightFixtureDefinitionFact> {
2687 playwright_fixture_definition_facts(self.semantic_facts)
2688 .cloned()
2689 .collect()
2690 }
2691
2692 /// Collect Playwright fixture-alias facts.
2693 pub fn playwright_fixture_aliases(self) -> Vec<PlaywrightFixtureAliasFact> {
2694 playwright_fixture_alias_facts(self.semantic_facts)
2695 .cloned()
2696 .collect()
2697 }
2698
2699 /// Collect conditional Playwright fixture-definition facts.
2700 pub fn playwright_conditional_fixture_definitions(
2701 self,
2702 ) -> Vec<PlaywrightConditionalFixtureDefinitionFact> {
2703 self.semantic_facts
2704 .iter()
2705 .filter_map(|fact| match fact {
2706 SemanticFact::PlaywrightConditionalFixtureDefinition(access) => {
2707 Some(access.as_ref().clone())
2708 }
2709 _ => None,
2710 })
2711 .collect()
2712 }
2713
2714 /// Collect the names of proven Playwright test bindings.
2715 pub fn playwright_test_bindings(self) -> Vec<PlaywrightTestBindingFact> {
2716 self.semantic_facts
2717 .iter()
2718 .filter_map(|fact| match fact {
2719 SemanticFact::PlaywrightTestBinding(binding) => Some(binding.clone()),
2720 _ => None,
2721 })
2722 .collect()
2723 }
2724
2725 /// Collect Playwright fixture-type facts.
2726 pub fn playwright_fixture_types(self) -> Vec<PlaywrightFixtureTypeFact> {
2727 playwright_fixture_type_facts(self.semantic_facts)
2728 .cloned()
2729 .collect()
2730 }
2731}
2732
2733/// Iterate ordinary whole-object uses.
2734pub fn ordinary_whole_object_uses(whole_object_uses: &[String]) -> impl Iterator<Item = &str> {
2735 whole_object_uses.iter().map(String::as_str)
2736}
2737
2738/// Iterate typed instance-export binding facts.
2739fn instance_export_binding_facts(
2740 semantic_facts: &[SemanticFact],
2741) -> impl Iterator<Item = &InstanceExportBindingFact> {
2742 semantic_facts.iter().filter_map(|fact| {
2743 if let SemanticFact::InstanceExportBinding(access) = fact {
2744 Some(access)
2745 } else {
2746 None
2747 }
2748 })
2749}
2750
2751fn exported_object_instance_property_facts(
2752 semantic_facts: &[SemanticFact],
2753) -> impl Iterator<Item = &ExportedObjectInstancePropertyFact> {
2754 semantic_facts.iter().filter_map(|fact| {
2755 if let SemanticFact::ExportedObjectInstanceProperty(property) = fact {
2756 Some(property)
2757 } else {
2758 None
2759 }
2760 })
2761}
2762
2763fn qualified_class_member_access_facts(
2764 semantic_facts: &[SemanticFact],
2765) -> impl Iterator<Item = &QualifiedClassMemberAccessFact> {
2766 semantic_facts.iter().filter_map(|fact| {
2767 if let SemanticFact::QualifiedClassMemberAccess(access) = fact {
2768 Some(access)
2769 } else {
2770 None
2771 }
2772 })
2773}
2774
2775fn class_this_member_access_facts(
2776 semantic_facts: &[SemanticFact],
2777) -> impl Iterator<Item = &ClassThisMemberAccessFact> {
2778 semantic_facts.iter().filter_map(|fact| {
2779 if let SemanticFact::ClassThisMemberAccess(access) = fact {
2780 Some(access)
2781 } else {
2782 None
2783 }
2784 })
2785}
2786
2787fn class_this_whole_object_use_facts(
2788 semantic_facts: &[SemanticFact],
2789) -> impl Iterator<Item = &ClassThisWholeObjectUseFact> {
2790 semantic_facts.iter().filter_map(|fact| {
2791 if let SemanticFact::ClassThisWholeObjectUse(access) = fact {
2792 Some(access)
2793 } else {
2794 None
2795 }
2796 })
2797}
2798
2799fn angular_component_field_array_type_facts(
2800 semantic_facts: &[SemanticFact],
2801) -> impl Iterator<Item = &AngularComponentFieldArrayTypeFact> {
2802 semantic_facts.iter().filter_map(|fact| {
2803 if let SemanticFact::AngularComponentFieldArrayType(access) = fact {
2804 Some(access)
2805 } else {
2806 None
2807 }
2808 })
2809}
2810
2811/// Iterate typed factory-call member facts.
2812fn factory_call_member_access_facts(
2813 semantic_facts: &[SemanticFact],
2814) -> impl Iterator<Item = &FactoryCallMemberAccessFact> {
2815 semantic_facts.iter().filter_map(|fact| {
2816 if let SemanticFact::FactoryCallMemberAccess(access) = fact {
2817 Some(access)
2818 } else {
2819 None
2820 }
2821 })
2822}
2823
2824/// Iterate typed free-function factory-return member facts.
2825fn factory_fn_member_access_facts(
2826 semantic_facts: &[SemanticFact],
2827) -> impl Iterator<Item = &FactoryFnMemberAccessFact> {
2828 semantic_facts.iter().filter_map(|fact| {
2829 if let SemanticFact::FactoryFnMemberAccess(access) = fact {
2830 Some(access)
2831 } else {
2832 None
2833 }
2834 })
2835}
2836
2837fn factory_fn_whole_object_facts(
2838 semantic_facts: &[SemanticFact],
2839) -> impl Iterator<Item = &FactoryFnWholeObjectFact> {
2840 semantic_facts.iter().filter_map(|fact| {
2841 if let SemanticFact::FactoryFnWholeObject(fact) = fact {
2842 Some(fact)
2843 } else {
2844 None
2845 }
2846 })
2847}
2848
2849/// Iterate object-literal factory-return property member facts.
2850fn factory_return_object_property_access_facts(
2851 semantic_facts: &[SemanticFact],
2852) -> impl Iterator<Item = &FactoryReturnObjectPropertyAccessFact> {
2853 semantic_facts.iter().filter_map(|fact| {
2854 if let SemanticFact::FactoryReturnObjectPropertyAccess(access) = fact {
2855 Some(access)
2856 } else {
2857 None
2858 }
2859 })
2860}
2861
2862/// Iterate typed fluent-chain member facts.
2863fn fluent_chain_member_access_facts(
2864 semantic_facts: &[SemanticFact],
2865) -> impl Iterator<Item = &FluentChainMemberAccessFact> {
2866 semantic_facts.iter().filter_map(|fact| {
2867 if let SemanticFact::FluentChainMemberAccess(access) = fact {
2868 Some(access)
2869 } else {
2870 None
2871 }
2872 })
2873}
2874
2875/// Iterate typed-property-hop member facts.
2876fn typed_property_member_access_facts(
2877 semantic_facts: &[SemanticFact],
2878) -> impl Iterator<Item = &TypedPropertyMemberAccessFact> {
2879 semantic_facts.iter().filter_map(|fact| {
2880 if let SemanticFact::TypedPropertyMemberAccess(access) = fact {
2881 Some(access)
2882 } else {
2883 None
2884 }
2885 })
2886}
2887
2888fn required_type_member_facts(
2889 semantic_facts: &[SemanticFact],
2890) -> impl Iterator<Item = &RequiredTypeMemberFact> {
2891 semantic_facts.iter().filter_map(|fact| {
2892 if let SemanticFact::RequiredTypeMember(required) = fact {
2893 Some(required)
2894 } else {
2895 None
2896 }
2897 })
2898}
2899
2900fn type_alias_surface_target_facts(
2901 semantic_facts: &[SemanticFact],
2902) -> impl Iterator<Item = &TypeAliasSurfaceTargetFact> {
2903 semantic_facts.iter().filter_map(|fact| {
2904 if let SemanticFact::TypeAliasSurfaceTarget(fact) = fact {
2905 Some(fact)
2906 } else {
2907 None
2908 }
2909 })
2910}
2911
2912fn string_enum_member_value_facts(
2913 semantic_facts: &[SemanticFact],
2914) -> impl Iterator<Item = &StringEnumMemberValueFact> {
2915 semantic_facts.iter().filter_map(|fact| {
2916 if let SemanticFact::StringEnumMemberValue(fact) = fact {
2917 Some(fact)
2918 } else {
2919 None
2920 }
2921 })
2922}
2923
2924fn computed_enum_key_use_facts(
2925 semantic_facts: &[SemanticFact],
2926) -> impl Iterator<Item = &ComputedEnumKeyUseFact> {
2927 semantic_facts.iter().filter_map(|fact| {
2928 if let SemanticFact::ComputedEnumKeyUse(fact) = fact {
2929 Some(fact)
2930 } else {
2931 None
2932 }
2933 })
2934}
2935
2936/// Iterate typed constructor-rooted fluent-chain member facts.
2937fn fluent_chain_new_member_access_facts(
2938 semantic_facts: &[SemanticFact],
2939) -> impl Iterator<Item = &FluentChainNewMemberAccessFact> {
2940 semantic_facts.iter().filter_map(|fact| {
2941 if let SemanticFact::FluentChainNewMemberAccess(access) = fact {
2942 Some(access)
2943 } else {
2944 None
2945 }
2946 })
2947}
2948
2949/// A member name referenced from an Angular template surface.
2950#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2951#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2952pub struct AngularTemplateMemberAccessFact {
2953 /// Referenced class member name.
2954 pub member: String,
2955}
2956
2957/// A typed Angular component field that exposes array elements to templates.
2958#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2959#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2960pub struct AngularComponentFieldArrayTypeFact {
2961 /// Component field name used as the template iterable.
2962 pub field: String,
2963 /// Array element class name.
2964 pub element_class: String,
2965}
2966
2967/// Opaque Angular `{ ...this }` forwarding marker.
2968#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2969#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2970pub struct AngularThisSpreadFact;
2971
2972/// A member access on a static factory call result.
2973#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2974#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2975pub struct FactoryCallMemberAccessFact {
2976 /// Local imported class or namespace object used as the factory callee.
2977 pub callee_object: String,
2978 /// Static factory method invoked on the callee object.
2979 pub callee_method: String,
2980 /// Member accessed on the returned instance-like object.
2981 pub member: String,
2982}
2983
2984/// A factory-returned value consumed opaquely, so every member of the class it
2985/// returns must be treated as used.
2986#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2987#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2988pub struct FactoryFnWholeObjectFact {
2989 /// Local imported function used as the factory callee.
2990 pub callee_name: String,
2991}
2992
2993/// A member access reached through a property of a value returned by an imported
2994/// factory that returns an object literal.
2995///
2996/// `const ui = createUi(); ui.orders.member` emits one fact per member read on a
2997/// factory-result property. The analyze layer resolves `callee_name` through the
2998/// consumer's imports to the factory's origin module, reads that module's
2999/// `exported_factory_return_object_shapes` to find the property whose path equals
3000/// `property_path` and its class local name, resolves THAT through the factory
3001/// module's own imports to the class export, and credits `member` on the class
3002/// (gated on the export actually being a class with members). See issue #1858.
3003#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3004#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3005pub struct FactoryReturnObjectPropertyAccessFact {
3006 /// Local imported function used as the factory callee.
3007 pub callee_name: String,
3008 /// Dotted property path between the factory-result local and the final member
3009 /// (e.g. `"orders"` for `ui.orders.member`, `"invoke.orders"` for `ui.invoke.orders.member`).
3010 pub property_path: String,
3011 /// Member accessed on the terminal property's instance.
3012 pub member: String,
3013}
3014
3015/// A member access reached through a typed property hop that the extraction
3016/// layer could not resolve locally.
3017///
3018/// `constructor(private opts: Opts) { ... this.opts.c.optM() }` where `Opts`
3019/// is NOT declared in this file emits
3020/// `TypedPropertyMemberAccessFact { type_name: "Opts", property_path: "c", member: "optM" }`.
3021/// The analyze layer resolves `type_name` through the consumer's imports to the
3022/// declaring module, walks `property_path` through that module's
3023/// `type_member_types`, resolves the terminal type name through the declaring
3024/// module's own imports, and credits `member` on the resolved class (gated on
3025/// the export actually being a class with members). See issue #1785.
3026#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3027#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3028pub struct TypedPropertyMemberAccessFact {
3029 /// Local (usually imported) named-type symbol the receiver is typed by.
3030 pub type_name: String,
3031 /// Remaining dotted property segments between the typed binding and the
3032 /// final member (e.g. `"c"` for `this.opts.c.optM()`).
3033 pub property_path: String,
3034 /// Member accessed on the terminal property's instance.
3035 pub member: String,
3036}
3037
3038/// A class member directly required by a named structural type.
3039///
3040/// Optional properties and methods are excluded: removing an optional
3041/// implementation can preserve assignability, while removing a required one
3042/// from an explicit `implements` contract cannot.
3043#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3044#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3045pub struct RequiredTypeMemberFact {
3046 /// Module-local interface or object-type alias name.
3047 pub type_name: String,
3048 /// Static required property or method name.
3049 pub member: String,
3050}
3051
3052/// One direct contributor to a named type alias's receiver surface.
3053///
3054/// Nested property types are deliberately excluded: in
3055/// `{ nested: Nested }`, `Alias.member` does not access `Nested.member`.
3056#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3057#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3058pub struct TypeAliasSurfaceTargetFact {
3059 /// Module-local alias declaration name.
3060 pub alias_name: String,
3061 /// Module-local or imported named type contributing the direct surface.
3062 pub target_name: String,
3063}
3064
3065/// A statically known string value of a TypeScript enum member.
3066#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3067#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3068pub struct StringEnumMemberValueFact {
3069 /// Module-local enum declaration name.
3070 pub enum_name: String,
3071 /// Static enum member name.
3072 pub member_name: String,
3073 /// Exact string initializer value.
3074 pub value: String,
3075}
3076
3077/// A computed property access whose key is a static enum member.
3078#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3079#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3080pub struct ComputedEnumKeyUseFact {
3081 /// Local enum object used as the key source.
3082 pub key_object: String,
3083 /// Static member selected from the enum object.
3084 pub key_member: String,
3085}
3086
3087/// A fluent chain rooted at a static factory call, one fact per chain. A step is
3088/// used when the root method is a factory and each earlier step returns `this`.
3089#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3090#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3091pub struct FluentChainMemberAccessFact {
3092 /// Local imported class or namespace object used as the chain root.
3093 pub root_object: String,
3094 /// Static factory method that starts the fluent chain.
3095 pub root_method: String,
3096 /// The methods called after the root method, each once, in first-call order.
3097 pub steps: Vec<String>,
3098}
3099
3100/// A fluent chain rooted at a `new` expression, one fact per chain. A step is
3101/// used when the first method and each earlier step return `this`.
3102#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3103#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3104pub struct FluentChainNewMemberAccessFact {
3105 /// Local imported class constructed by the `new` expression.
3106 pub class_name: String,
3107 /// The method called on the new instance.
3108 pub first_method: String,
3109 /// The methods called after the first method, each once, in first-call order.
3110 pub steps: Vec<String>,
3111}
3112
3113/// A member access on a Playwright fixture object inside a test callback.
3114#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3115#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3116pub struct PlaywrightFixtureUseFact {
3117 /// Local test function or wrapper used as the callback callee.
3118 pub test_name: String,
3119 /// Fixture name or dotted fixture path referenced in the callback.
3120 pub fixture_name: String,
3121 /// Member accessed on the fixture target.
3122 pub member: String,
3123}
3124
3125/// A Playwright fixture definition declared by a typed `test.extend<T>()`.
3126#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3127#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3128pub struct PlaywrightFixtureDefinitionFact {
3129 /// Local test function or wrapper receiving the fixture definition.
3130 pub test_name: String,
3131 /// Fixture name or dotted fixture path declared by the fixture type.
3132 pub fixture_name: String,
3133 /// Local type symbol used as the fixture target.
3134 pub type_name: String,
3135}
3136
3137/// A Playwright fixture definition from `<base>.extend<T>()` where `base` is
3138/// an imported name. The extractor cannot prove that `base` holds a Playwright
3139/// test, so analysis applies the definition only when `base` resolves to one.
3140#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3141#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3142pub struct PlaywrightConditionalFixtureDefinitionFact {
3143 /// Local test function or wrapper receiving the fixture definition.
3144 pub test_name: String,
3145 /// Imported local name that `.extend<T>()` is called on.
3146 pub base_name: String,
3147 /// Fixture name or dotted fixture path declared by the fixture type.
3148 pub fixture_name: String,
3149 /// Local type symbol used as the fixture target.
3150 pub type_name: String,
3151}
3152
3153/// A local name that holds a Playwright test: the result of an `.extend()` on
3154/// the `@playwright/test` `test` import or of a `mergeTests(...)` call.
3155#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3156#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3157pub struct PlaywrightTestBindingFact {
3158 /// Local name of the Playwright test.
3159 pub test_name: String,
3160}
3161
3162/// A Playwright fixture wrapper alias declared by `mergeTests` or `.extend`.
3163#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3164#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3165pub struct PlaywrightFixtureAliasFact {
3166 /// Local test function or wrapper that inherits fixture definitions.
3167 pub test_name: String,
3168 /// Local test function or wrapper inherited by `test_name`.
3169 pub base_name: String,
3170}
3171
3172/// A nested Playwright fixture binding declared by a fixture type alias.
3173#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3174#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3175pub struct PlaywrightFixtureTypeFact {
3176 /// Local type alias containing the nested fixture binding.
3177 pub alias_name: String,
3178 /// Fixture name or dotted fixture path declared inside the type alias.
3179 pub fixture_name: String,
3180 /// Local type symbol used as the nested fixture target.
3181 pub type_name: String,
3182}
3183
3184/// An exported value whose runtime instance targets a local class or interface.
3185#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3186#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3187pub struct InstanceExportBindingFact {
3188 /// Exported binding name.
3189 pub export_name: String,
3190 /// Local class or interface symbol used as the instance target.
3191 pub target_name: String,
3192}
3193
3194/// A property of an exported object whose value is an instance of a local class.
3195#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3196#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3197pub struct ExportedObjectInstancePropertyFact {
3198 /// Public export name of the containing object.
3199 pub export_name: String,
3200 /// Dotted path from the exported object to the instance property.
3201 pub property_path: String,
3202 /// Local class symbol instantiated at that property.
3203 pub class_local_name: String,
3204}
3205
3206/// A proven class member read through a namespace-qualified constructor or local subclass.
3207#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3208#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3209pub struct QualifiedClassMemberAccessFact {
3210 /// Local namespace-import binding.
3211 pub namespace_local: String,
3212 /// Class export selected from that namespace.
3213 pub class_export_name: String,
3214 /// Member accessed through the proven class or instance binding.
3215 pub member: String,
3216}
3217
3218/// Opaque marker for a dynamic custom-element render site.
3219#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3220#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3221pub struct DynamicCustomElementRenderFact;
3222
3223/// The action performed by a Vitest module-mock operation.
3224#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3225#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3226#[serde(rename_all = "snake_case")]
3227pub enum VitestModuleMockAction {
3228 /// Register a mock. `factory_replaces_original` is true only when the
3229 /// factory is structurally closed and cannot load the original module.
3230 ///
3231 /// Automock (`vi.mock` / `jest.mock` without a factory) is always
3232 /// `factory_replaces_original: false` by decision (issue #2082). For
3233 /// Vitest, the runner derives the mocked shape by importing the original
3234 /// module, so its top-level code executes at collection time, and
3235 /// file-level masking cannot express "module evaluated but exports
3236 /// stubbed". For Jest, a `__mocks__` sibling takes precedence and the
3237 /// original is genuinely not required, but the manual mock itself may
3238 /// load the original (`jest.requireActual`), and proving it never does
3239 /// would need a cross-file factory proof. Both runners therefore keep
3240 /// coverage credit for the automock form.
3241 Mock {
3242 /// Whether the factory provably replaces the original module.
3243 factory_replaces_original: bool,
3244 },
3245 /// Remove a registered mock and restore the original module.
3246 Unmock,
3247}
3248
3249impl VitestModuleMockAction {
3250 /// Whether this operation registers a proven complete replacement.
3251 #[must_use]
3252 pub const fn replaces_original(self) -> bool {
3253 matches!(
3254 self,
3255 Self::Mock {
3256 factory_replaces_original: true
3257 }
3258 )
3259 }
3260}
3261
3262/// Ordered Vitest module-mock operation with a static source target.
3263///
3264/// The declaring [`ModuleInfo::file_id`] owns the test-root provenance. The
3265/// resolver consumes `source` through its canonical specifier pipeline; this
3266/// fact deliberately carries no resolved path or duplicate diagnostic span.
3267#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3268#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3269pub struct VitestModuleMockOperationFact {
3270 /// Static module specifier passed to `vi.mock` or `vi.unmock`.
3271 pub source: String,
3272 /// Source-order position of the call within the declaring module.
3273 pub call_start: u32,
3274 /// Typed mock or unmock action.
3275 pub action: VitestModuleMockAction,
3276}
3277
3278/// A `this`-rooted member access with exact enclosing-class provenance.
3279#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3280#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3281pub struct ClassThisMemberAccessFact {
3282 /// Enclosing class local name, or `default` for an anonymous default class.
3283 pub class_local_name: String,
3284 /// Dotted receiver spelling beginning with `this.`.
3285 pub object: String,
3286 /// Terminal member being accessed.
3287 pub member: String,
3288}
3289
3290/// A whole-object use of a `this`-rooted chain with enclosing-class provenance.
3291#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3292#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3293pub struct ClassThisWholeObjectUseFact {
3294 /// Enclosing class local name, or `default` for an anonymous default class.
3295 pub class_local_name: String,
3296 /// Dotted receiver spelling beginning with `this.`.
3297 pub object: String,
3298}
3299
3300/// A `"use client"` / `"use server"` directive string written as an expression
3301/// statement in `program.body` (NOT the leading prologue), so the RSC bundler
3302/// silently ignores it. One entry per offending occurrence. Consumed by the
3303/// `misplaced-directive` detector.
3304#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3305pub struct MisplacedDirectiveSite {
3306 /// `true` for `"use server"`, `false` for `"use client"`.
3307 pub is_server: bool,
3308 /// Start byte offset of the misplaced directive statement.
3309 pub span_start: u32,
3310}
3311
3312/// Which side of a dependency-injection link a call site represents.
3313#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3314pub enum DiRole {
3315 /// `provide(KEY, value)` / `app.provide(KEY, value)` / `setContext(KEY, value)`.
3316 Provide,
3317 /// `inject(KEY)` / `getContext(KEY)`.
3318 Inject,
3319}
3320
3321/// Which framework's DI API a call site came from (drives the finding message).
3322#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3323pub enum DiFramework {
3324 /// Vue `provide` / `inject` (from `vue` / `@vue/runtime-core`).
3325 Vue,
3326 /// Svelte `setContext` / `getContext` (from `svelte`).
3327 Svelte,
3328 /// Angular `inject(TOKEN)` / `@Inject(TOKEN)` (from `@angular/core`),
3329 /// matched against `{ provide: TOKEN, ... }` provider objects.
3330 Angular,
3331}
3332
3333/// A Vue `provide`/`inject` or Svelte `setContext`/`getContext` call site keyed
3334/// by an identifier symbol. The `key_local` is resolved at analyze time through
3335/// the consuming module's import/export tables to a canonical defining-site
3336/// export key, so a provide and an inject of the same shared symbol unify even
3337/// across barrel re-exports. Consumed by the `unprovided-inject` detector.
3338#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3339pub struct DiKeySite {
3340 /// The key identifier as written at the call site.
3341 pub key_local: String,
3342 /// Whether this is a provide or an inject.
3343 pub role: DiRole,
3344 /// Which framework's API this came from.
3345 pub framework: DiFramework,
3346 /// Start byte offset of the call expression (anchors the finding).
3347 pub span_start: u32,
3348}
3349
3350/// A component prop declared by Vue `<script setup>` `defineProps` or Svelte 5
3351/// `$props()`. `used_in_script` / `used_in_template` are set during extraction;
3352/// the `unused-component-prop` detector flags a prop where neither is true. See
3353/// `harvest_define_props` and `harvest_svelte_props` in `sfc_props.rs`.
3354#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3355pub struct ComponentProp {
3356 /// The declared prop name.
3357 pub name: String,
3358 /// The template/script-visible local binding name: the destructure alias for
3359 /// `const { name: alias } = defineProps()` or
3360 /// `let { name: alias } = $props()`, otherwise the prop name itself. A
3361 /// renamed prop is read through this local, so usage must be checked against
3362 /// it, not the declared name.
3363 pub local: String,
3364 /// Start byte offset of the prop declaration (anchors the finding).
3365 pub span_start: u32,
3366 /// Whether this prop is referenced in the component's `<script>` (a
3367 /// destructured local binding with a resolved reference, or a `props.<name>`
3368 /// member access). For React, this is set-in-body: a resolved reference to the
3369 /// destructured local anywhere in the component function body.
3370 pub used_in_script: bool,
3371 /// Whether this prop name is referenced in the component's `<template>`.
3372 /// Set by `apply_template_usage` when the template scanner credits the name.
3373 /// Always false for React (no template; React uses `used_in_script`).
3374 pub used_in_template: bool,
3375 /// The enclosing component name. Empty for Vue SFCs (one component per file,
3376 /// the file stem is the component, set by the detector). For React this is the
3377 /// component function/arrow name a prop was declared on, so the detector can
3378 /// emit the right `component_name` and apply the per-component abstain ladder
3379 /// (a file can declare several React components).
3380 pub component: String,
3381 /// React-only: `true` when the destructured prop local is referenced at least
3382 /// once OUTSIDE a child-JSX attribute value expression (a substantive
3383 /// consumption: a hook arg, a host-element child, a non-JSX-attr read). When
3384 /// `used_in_script` is true but this is false, the prop is referenced ONLY as
3385 /// the root of forwarded child attribute values, i.e. a pure pass-through.
3386 /// Always `false` for Vue (no forward-vs-consume distinction is computed).
3387 pub used_outside_forward: bool,
3388}
3389
3390/// A Vue `<script setup>` `defineEmits` declared event, harvested from the type
3391/// tuple-call form (`defineEmits<{ (e: 'foo'): void }>()`), the type object form
3392/// (`defineEmits<{ foo: [x: string] }>()`), or the runtime array form
3393/// (`defineEmits(['foo'])`). `used` is set during extraction when the bound emit
3394/// name is called as `emit('<name>')`. The `unused-component-emit` detector flags
3395/// an event where `used` is false. See `harvest_define_emits` in `sfc_props.rs`.
3396#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3397pub struct ComponentEmit {
3398 /// The declared emit event name.
3399 pub name: String,
3400 /// Start byte offset of the emit declaration (anchors the finding).
3401 pub span_start: u32,
3402 /// Whether this event is emitted via `emit('<name>')` somewhere in the
3403 /// component's `<script>`.
3404 pub used: bool,
3405}
3406
3407/// A Svelte custom event dispatched via `dispatch('<name>')`, where `dispatch`
3408/// is the binding from a `const dispatch = createEventDispatcher()` call. Only
3409/// literal-first-arg dispatches are recorded; a `dispatch(<nonLiteral>)` sets
3410/// `ModuleInfo::has_dynamic_dispatch` instead. Consumed by the
3411/// `unused-svelte-event` detector, which flags an event dispatched here but
3412/// listened to nowhere project-wide (the cross-file dead-output direction). The
3413/// span is a byte offset (not an `oxc_span::Span`) so the type round-trips
3414/// through the bitcode cache directly, mirroring `ComponentEmit::span_start`.
3415#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3416pub struct DispatchedEvent {
3417 /// The dispatched event name (the literal first argument).
3418 pub name: String,
3419 /// Start byte offset of the `dispatch(...)` call (anchors the finding).
3420 pub span_start: u32,
3421}
3422
3423/// A declared Angular component/directive input, harvested from an `@Input()`
3424/// decorator or a signal `input()` / `input.required()` / `model()` initializer
3425/// on an Angular-decorated class. Consumed by the `unused-component-input`
3426/// detector, which flags an input read nowhere in its own component (neither the
3427/// template nor the class body). The span is stored as a byte offset (not an
3428/// `oxc_span::Span`) so the type is cheap to mirror onto the cache, matching
3429/// `ComponentEmit::span_start`. `ModuleInfo` is not serialized, so no serde
3430/// attrs are derived here. `bitcode` derives let the type be mirrored directly
3431/// onto `CachedModule` (the same pattern as `ComponentEmit`).
3432#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3433pub struct AngularInputMember {
3434 /// The declared input name (the property key).
3435 pub name: String,
3436 /// Start byte offset of the property key (anchors the finding).
3437 pub span_start: u32,
3438}
3439
3440/// A declared Angular component/directive output, harvested from an `@Output()`
3441/// decorator or a signal `output()` / `outputFromObservable()` initializer on an
3442/// Angular-decorated class. Consumed by the `unused-component-output` detector,
3443/// which flags an output emitted nowhere in its own component. A `model()` is an
3444/// input and a framework-driven output, so it is recorded ONLY as an input and
3445/// never appears here (the implicit `update:` emit is framework-managed). The
3446/// span is a byte offset for the same reason as `AngularInputMember`.
3447#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3448pub struct AngularOutputMember {
3449 /// The declared output name (the property key).
3450 pub name: String,
3451 /// Start byte offset of the property key (anchors the finding).
3452 pub span_start: u32,
3453}
3454
3455/// A declared Angular `@Component` and its `selector` value(s), harvested from a
3456/// `@Component({ selector: '...' })` decorator. Consumed by the Angular arm of
3457/// the `unrendered-component` detector, which flags a component whose every
3458/// element selector is used in NO template project-wide (and that is not
3459/// referenced by class name anywhere, e.g. routed / bootstrapped / dynamically
3460/// rendered). A multi-selector string (`'app-foo, [appBar]'`) is split into the
3461/// `selectors` list. The span is stored as a byte offset (not an
3462/// `oxc_span::Span`) so the type round-trips through the bitcode cache directly,
3463/// mirroring `AngularInputMember::span_start`. `@Directive` is intentionally NOT
3464/// harvested here (directives have no template render). `ModuleInfo` is not
3465/// serialized, so no serde attrs are derived.
3466#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3467pub struct AngularComponentSelector {
3468 /// The declared selector strings for this component, split on `,`. A purely
3469 /// element-selector component has only `app-foo`-shaped entries; attribute
3470 /// (`[appFoo]`) and class (`.foo`) selectors are retained verbatim so the
3471 /// detector can abstain when ANY non-element selector is present.
3472 pub selectors: Vec<String>,
3473 /// Start byte offset of the component class declaration (anchors the
3474 /// finding).
3475 pub span_start: u32,
3476 /// The component class name (used to credit routed / bootstrapped / dynamic
3477 /// class-name references project-wide).
3478 pub class_name: String,
3479}
3480
3481/// A Lit / web-component custom element registered in a module via
3482/// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed by
3483/// the Lit arm of the `unrendered-component` detector. The span is stored as a
3484/// byte offset (not an `oxc_span::Span`) so the type round-trips through the
3485/// bitcode cache directly, mirroring `AngularComponentSelector::span_start`.
3486#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3487pub struct RegisteredCustomElement {
3488 /// The registered custom-element tag name (`x-foo`).
3489 pub tag: String,
3490 /// The registering class's local name, used for the public-API / export
3491 /// abstain (an exported / published element is rendered by a downstream
3492 /// consumer the scan cannot see). Empty for an anonymous
3493 /// `export default @customElement('x-foo') class extends LitElement {}`.
3494 pub class_local_name: String,
3495 /// Start byte offset of the registering class declaration (anchors the
3496 /// finding at the element, NOT line 1, since a `.ts` file can register
3497 /// several custom elements).
3498 pub span_start: u32,
3499}
3500
3501/// A key returned from a SvelteKit route `load()` function's terminal return
3502/// object literal. Harvested from `+page.{ts,server.ts,js,server.js}` files
3503/// exporting a `load` function. Consumed by the `unused-load-data-key` detector,
3504/// which flags a key read by no consumer. The span is stored as byte offsets
3505/// (not an `oxc_span::Span`) so the type round-trips through the bitcode cache
3506/// directly, mirroring `DiKeySite::span_start` / `ComponentEmit::span_start`.
3507#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3508pub struct LoadReturnKey {
3509 /// The returned-object property key name.
3510 pub name: String,
3511 /// Start byte offset of the key (anchors the finding).
3512 pub span_start: u32,
3513 /// End byte offset of the key.
3514 pub span_end: u32,
3515}
3516
3517/// The syntactic shape of an identified React component definition. Drives the
3518/// abstain ladder later phases apply: a `forwardRef` / `memo` wrapper whose
3519/// props come from an imported interface fallow cannot resolve must abstain
3520/// (ADR-001), not guess.
3521#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3522pub enum ComponentFunctionKind {
3523 /// A `function Foo() { return <.../> }` declaration.
3524 FnDecl,
3525 /// A `const Foo = () => <.../>` arrow (or function-expression) binding.
3526 Arrow,
3527 /// A `const Foo = forwardRef((props, ref) => <.../>)` wrapper.
3528 ForwardRefWrapper,
3529 /// A `const Foo = memo((props) => <.../>)` wrapper.
3530 MemoWrapper,
3531}
3532
3533/// An identified React component: a function/arrow whose body returns JSX.
3534/// Captured by `visit_jsx_element`'s enclosing-component tracking. The
3535/// `unused-component-prop` (React arm) and complexity-fold phases consume this;
3536/// the abstain flags keep zero-FP on the cases ADR-001 cannot resolve.
3537#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3538pub struct ComponentFunction {
3539 /// The component name (the binding or declaration identifier).
3540 pub name: String,
3541 /// Start byte offset of the component definition (anchors findings).
3542 pub span_start: u32,
3543 /// The syntactic shape of the definition.
3544 pub kind: ComponentFunctionKind,
3545 /// Whether the component is exported from its module (a named export, a
3546 /// `export default`, or re-exported in the same module). Public-API
3547 /// components abstain in the prop phase.
3548 pub is_exported: bool,
3549 /// `true` when the component's props are not statically harvestable: a
3550 /// rest/spread in the signature (`{ ...rest }`), props passed wholesale to a
3551 /// hook/helper, or a `forwardRef` / `memo` wrapper whose props come from an
3552 /// imported interface generic fallow cannot resolve (ADR-001). The prop
3553 /// phase abstains on the whole component when set.
3554 pub has_unharvestable_props: bool,
3555 /// `true` when the component body calls `cloneElement` / `React.cloneElement`.
3556 /// `cloneElement` injects props by reflection, so the static forward-set is
3557 /// incomplete; the prop-drilling phase abstains on any chain through this
3558 /// component (ADR-001, zero-FP).
3559 pub uses_clone_element: bool,
3560 /// `true` when the component renders a `*.Provider` member-expression tag
3561 /// (`<FooContext.Provider>`). A context provider in the subtree means the
3562 /// drilling may be a deliberate non-context choice (or the prop is about to
3563 /// be provided); the prop-drilling phase downgrades/abstains.
3564 pub renders_provider: bool,
3565 /// `true` when the component passes a function as a child render value
3566 /// (render-props / children-as-function: `<Foo>{() => ...}</Foo>` or
3567 /// `<Foo render={() => ...}/>`). The forwarded shape is dynamic; the
3568 /// prop-drilling phase abstains on chains through this component.
3569 pub has_children_as_function: bool,
3570 /// `true` when the component body is pure structural indirection: a single
3571 /// statement returning exactly one capitalized/member-expression JSX element
3572 /// (no host wrapper, no extra children, optionally a fragment wrapping a
3573 /// single element) that forwards props via a bare spread of the component's
3574 /// own props binding / rest local (`<Child {...props}/>`), with NO named
3575 /// attributes alongside the spread and NO self-render. The cross-component
3576 /// `thin-wrapper` phase joins this with hook-density / cyclomatic checks and
3577 /// the resolved single render edge to flag a component that is a candidate
3578 /// for inlining. Computed from the component's own AST only, so it caches
3579 /// byte-identity-safe (ADR-001).
3580 pub is_pure_passthrough: bool,
3581}
3582
3583/// The kind of a React hook call. `Custom` covers any `use*`-named call that is
3584/// not one of the built-in hooks.
3585#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3586pub enum HookUseKind {
3587 /// `useState(...)`.
3588 UseState,
3589 /// `useEffect(...)`.
3590 UseEffect,
3591 /// `useMemo(...)`.
3592 UseMemo,
3593 /// `useCallback(...)`.
3594 UseCallback,
3595 /// Any other `use*`-named call (a custom hook).
3596 Custom,
3597}
3598
3599/// A React hook call site inside a component. Consumed by the complexity-fold
3600/// phase (hook density) and surfaced as descriptive hotspot context.
3601#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3602pub struct HookUse {
3603 /// The hook kind.
3604 pub kind: HookUseKind,
3605 /// The dependency-array arity, recorded ONLY when a literal array is present
3606 /// at the dependency-array position (`[a, b]` -> `Some(2)`, `[]` ->
3607 /// `Some(0)`). `None` when the call has no dependency array argument or the
3608 /// argument is not a literal array (ADR-001: do not guess).
3609 pub dep_array_arity: Option<u32>,
3610 /// Start byte offset of the hook call (anchors findings).
3611 pub span_start: u32,
3612 /// The enclosing component name (the top of the visitor's component stack
3613 /// when the hook call was recorded). Lets the descriptive per-component hook
3614 /// summary attribute hooks exactly even when a file declares several
3615 /// components. A hook recorded outside any component carries an empty string
3616 /// (the visitor only records hooks inside a component, so this is the
3617 /// rare top-level / unattributed case).
3618 pub component: String,
3619}
3620
3621/// A render edge: one component rendering another (a capitalized or
3622/// member-expression JSX tag). Captured at extraction time with the child's
3623/// written name; resolution of `child_component_name` to a `FileId`/export is
3624/// deferred to graph build via the existing import map.
3625#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3626pub struct RenderEdge {
3627 /// The name of the component that renders the child (the enclosing
3628 /// component). Empty when the JSX is not inside an identified component (a
3629 /// top-level render expression).
3630 pub parent_component: String,
3631 /// The rendered child component name as written (`Foo` or the full
3632 /// member-expression path `Foo.Bar`).
3633 pub child_component_name: String,
3634 /// The attribute (prop) names passed at the render site, in source order.
3635 pub attr_names: Vec<String>,
3636 /// `true` when the render site contains a JSX spread (`{...x}`), so the
3637 /// passed-prop set is not statically complete.
3638 pub has_spread: bool,
3639 /// The forwarded attributes at this render site: each pairs the child
3640 /// attribute NAME with the identifier ROOT of its value expression
3641 /// (`userName={user.name}` -> `{ attr: "userName", root: "user" }`;
3642 /// `value={x}` -> `{ attr: "value", root: "x" }`). ONLY plain identifier or
3643 /// member-root access values are recorded (`{x}`, `{x.y}`, `{x.y.z}`); a value
3644 /// that is a call, an arrow/function, a conditional, a JSX element, or any
3645 /// other complex expression is NOT recorded here (its root would not be a pure
3646 /// forward) and sets `has_complex_forward` instead. The prop-drilling chain
3647 /// walk uses this pairing to map "this component forwards prop P" to "the
3648 /// child receives it as attribute A".
3649 pub forward_attrs: Vec<ForwardAttr>,
3650 /// `true` when at least one attribute value at this render site is a complex
3651 /// expression (a call, an arrow/function render-prop, a conditional, a JSX
3652 /// element-as-prop, a template literal, etc.) whose identifier root was NOT
3653 /// recorded in `forward_attrs`. The prop-drilling phase abstains on a chain
3654 /// whose forwarded prop flows through such a value (ADR-001, zero-FP).
3655 pub has_complex_forward: bool,
3656}
3657
3658/// One forwarded JSX attribute: the child attribute name plus the identifier
3659/// root of its value expression. See [`RenderEdge::forward_attrs`].
3660#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3661pub struct ForwardAttr {
3662 /// The child attribute (prop) name as written (`userName`).
3663 pub attr: String,
3664 /// The identifier root of the attribute value expression (`user` for
3665 /// `userName={user.name}`).
3666 pub root: String,
3667}
3668
3669#[expect(
3670 clippy::trivially_copy_pass_by_ref,
3671 reason = "serde serialize_with requires &T"
3672)]
3673fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
3674 use serde::ser::SerializeMap;
3675 let mut map = serializer.serialize_map(Some(2))?;
3676 map.serialize_entry("start", &span.start)?;
3677 map.serialize_entry("end", &span.end)?;
3678 map.end()
3679}
3680
3681/// Export identifier.
3682#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
3683pub enum ExportName {
3684 /// A named export (e.g., `export const foo`).
3685 Named(String),
3686 /// The default export.
3687 Default,
3688}
3689
3690impl ExportName {
3691 /// Compare against a string without allocating (avoids `to_string()`).
3692 #[must_use]
3693 pub fn matches_str(&self, s: &str) -> bool {
3694 match self {
3695 Self::Named(n) => n == s,
3696 Self::Default => s == "default",
3697 }
3698 }
3699}
3700
3701impl std::fmt::Display for ExportName {
3702 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3703 match self {
3704 Self::Named(n) => write!(f, "{n}"),
3705 Self::Default => write!(f, "default"),
3706 }
3707 }
3708}
3709
3710/// An import declaration.
3711#[derive(Debug, Clone)]
3712pub struct ImportInfo {
3713 /// The import specifier (e.g., `./utils` or `react`).
3714 pub source: String,
3715 /// How the symbol is imported (named, default, namespace, or side-effect).
3716 pub imported_name: ImportedName,
3717 /// The local binding name in the importing module.
3718 pub local_name: String,
3719 /// Whether this is a type-only import (`import type`).
3720 pub is_type_only: bool,
3721 /// Whether this whole-module import forwards type meanings only.
3722 ///
3723 /// Set for `export type *` and `export type * as ns` inside a
3724 /// `declare module '...'` body (issue #2375). Those forms record the same
3725 /// bindingless whole-module shape the plain ambient star records
3726 /// (issue #2357), but the star they stand for erases every value meaning,
3727 /// so the graph credits the target's star surface in the type namespace
3728 /// alone. Every other import leaves this false: `is_type_only` already
3729 /// decides their namespace on its own.
3730 pub is_type_only_star: bool,
3731 /// Whether this import originated from a CSS-context.
3732 pub from_style: bool,
3733 /// Source span of the import declaration.
3734 pub span: Span,
3735 /// Span of the source string literal used by the LSP to highlight the specifier.
3736 pub source_span: Span,
3737}
3738
3739/// How a symbol is imported.
3740#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3741pub enum ImportedName {
3742 /// A named import (e.g., `import { foo }`).
3743 Named(String),
3744 /// A default import (e.g., `import React`).
3745 Default,
3746 /// A namespace import (e.g., `import * as utils`).
3747 Namespace,
3748 /// A side-effect import (e.g., `import './styles.css'`).
3749 SideEffect,
3750}
3751
3752#[cfg(target_pointer_width = "64")]
3753const _: () = assert!(std::mem::size_of::<ExportInfo>() == 152);
3754#[cfg(target_pointer_width = "64")]
3755const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
3756#[cfg(target_pointer_width = "64")]
3757const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
3758#[cfg(target_pointer_width = "64")]
3759const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
3760#[cfg(target_pointer_width = "64")]
3761const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
3762#[cfg(target_pointer_width = "64")]
3763const _: () = assert!(std::mem::size_of::<SemanticFact>() == 80);
3764#[cfg(target_pointer_width = "64")]
3765const _: () = assert!(std::mem::size_of::<SinkSite>() == 216);
3766#[cfg(target_pointer_width = "64")]
3767const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 1496);
3768#[cfg(target_pointer_width = "64")]
3769const _: () = assert!(std::mem::size_of::<ImportBindingReference>() == 64);
3770#[cfg(target_pointer_width = "64")]
3771const _: () = assert!(std::mem::size_of::<TypeMemberTypeEntry>() == 72);
3772
3773/// A re-export declaration.
3774#[derive(Debug, Clone)]
3775pub struct ReExportInfo {
3776 /// The module being re-exported from.
3777 pub source: String,
3778 /// The name imported from the source module (or `*` for star re-exports).
3779 pub imported_name: String,
3780 /// The name exported from this module.
3781 pub exported_name: String,
3782 /// Whether this is a type-only re-export.
3783 pub is_type_only: bool,
3784 /// Source span of the re-export declaration on this module.
3785 pub span: oxc_span::Span,
3786 /// Span of the whole re-export statement. A multi-binding statement
3787 /// yields one `ReExportInfo` per binding, each with a per-binding
3788 /// `span`; this field lets consumers reason about the enclosing
3789 /// statement (e.g. suppression coverage). Empty (`start == end`) for
3790 /// synthesized re-exports that have no single owning statement.
3791 pub statement_span: oxc_span::Span,
3792 /// Span of the source string literal (the specifier in quotes), used to
3793 /// anchor unresolved-import findings on the specifier. Empty
3794 /// (`start == end`) when no literal exists in the statement.
3795 pub source_span: oxc_span::Span,
3796}
3797
3798/// A dynamic `import()` call.
3799#[derive(Debug, Clone)]
3800pub struct DynamicImportInfo {
3801 /// The import specifier.
3802 pub source: String,
3803 /// Source span of the `import()` expression.
3804 pub span: Span,
3805 /// Names destructured from the dynamic import result.
3806 /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
3807 /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
3808 pub destructured_names: Vec<String>,
3809 /// The local variable name for `const x = await import(...)`.
3810 /// Used for namespace import narrowing via member access tracking.
3811 pub local_name: Option<String>,
3812 /// True when this dynamic import was synthesised by fallow rather than appearing in user source.
3813 pub is_speculative: bool,
3814 /// True when the value of an `import()` without a binding escapes, for
3815 /// example as a return value, a call argument, or an array element.
3816 /// The consumer can then read any export, so the edge credits the whole
3817 /// module namespace. False for a discarded `import()` statement, which
3818 /// only loads the module.
3819 pub value_escapes: bool,
3820}
3821
3822/// A `require()` call.
3823#[derive(Debug, Clone)]
3824pub struct RequireCallInfo {
3825 /// The require specifier.
3826 pub source: String,
3827 /// Source span of the `require()` call.
3828 pub span: Span,
3829 /// Span of the string-literal argument with quotes (`'./x'`), which anchors an
3830 /// `unresolved-import` diagnostic. `Span::default()` for a non-literal argument.
3831 pub source_span: Span,
3832 /// Names destructured from the `require()` result.
3833 pub destructured_names: Vec<String>,
3834 /// The `(key, local)` pair of each destructured identifier property:
3835 /// `const { exec: run } = require(...)` gives `("exec", "run")`.
3836 pub destructured_locals: Vec<(String, String)>,
3837 /// The local variable name for `const x = require(...)`.
3838 pub local_name: Option<String>,
3839 /// `true` for `import type X = require('...')`, the one require spelling
3840 /// TypeScript erases entirely: the emitted JavaScript contains no
3841 /// `require` call, so the target is a type-space reference and never a
3842 /// runtime dependency. Always `false` for `const x = require(...)`, which
3843 /// has no type-only spelling. Read by dependency classification so a
3844 /// type-only devDependency is not reported as production usage.
3845 pub is_type_only: bool,
3846}
3847
3848/// Result of parsing all files, including incremental cache statistics.
3849pub struct ParseResult {
3850 /// Extracted module information for all successfully parsed files.
3851 pub modules: Vec<ModuleInfo>,
3852 /// Files discovered with stable IDs but unreadable by the parser.
3853 pub read_failures: Vec<SourceReadFailure>,
3854 /// Files that parsed with diagnostics, so their extracted module may be
3855 /// incomplete. Reported, never used to withhold findings.
3856 pub parse_degradations: Vec<SourceParseDegradation>,
3857 /// Number of files whose parse results were loaded from cache (unchanged).
3858 pub cache_hits: usize,
3859 /// Number of files that required a full parse (new or changed).
3860 pub cache_misses: usize,
3861 /// Summed wall-clock time of the actual AST parses across all rayon workers.
3862 pub parse_cpu_ms: f64,
3863 /// Files whose bytes were read from disk: every parse, plus every cache
3864 /// hit that had to compare the content hash.
3865 pub files_read: u64,
3866 /// Bytes of source read from disk across all files.
3867 pub source_bytes_read: u64,
3868 /// Source bytes that the CSS comment mask read across all parsed files.
3869 pub css_masked_bytes: u64,
3870}
3871
3872/// A discovered source that could not be read as UTF-8 text.
3873#[derive(Debug, Clone, PartialEq, Eq)]
3874pub struct SourceReadFailure {
3875 /// Stable discovery identity retained even though no module was produced.
3876 pub file_id: FileId,
3877 /// Absolute discovered source path.
3878 pub path: PathBuf,
3879 /// Underlying filesystem or UTF-8 decoding error.
3880 pub error: String,
3881}
3882
3883/// A discovered source that was read but did not parse cleanly.
3884///
3885/// The module it produced is still analyzed: dropping it would turn one broken
3886/// file into project-wide silence. The point of carrying the degradation is
3887/// that the imports the file failed to parse credited nothing, so its targets
3888/// can be reported as unused with full confidence unless a consumer is told the
3889/// parse was partial.
3890#[derive(Debug, Clone, PartialEq, Eq)]
3891pub struct SourceParseDegradation {
3892 /// Stable discovery identity of the degraded source.
3893 pub file_id: FileId,
3894 /// Absolute discovered source path.
3895 pub path: PathBuf,
3896 /// Number of parser diagnostics reported for the file.
3897 pub error_count: u32,
3898 /// `true` when the parser abandoned the file instead of recovering.
3899 pub panicked: bool,
3900 /// The nesting cap when the file nests too deep to parse.
3901 pub nesting_limit: Option<u32>,
3902}
3903
3904#[path = "extract_effect.rs"]
3905mod effect;
3906pub use effect::*;
3907#[path = "extract_calls.rs"]
3908mod calls;
3909pub use calls::*;
3910#[path = "extract_factory.rs"]
3911mod factory;
3912pub use factory::*;
3913
3914#[cfg(test)]
3915#[path = "extract_tests.rs"]
3916mod tests;
3917
3918/// Framework owning a statically extracted component contract.
3919#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3920pub enum ComponentFramework {
3921 /// React JSX.
3922 React,
3923 /// Preact JSX.
3924 Preact,
3925 /// Solid JSX.
3926 Solid,
3927 /// Qwik JSX.
3928 Qwik,
3929 /// Vue and Nuxt single-file components.
3930 Vue,
3931 /// Svelte components.
3932 Svelte,
3933 /// Astro components.
3934 Astro,
3935 /// Angular components and directives.
3936 Angular,
3937 /// Lit custom elements.
3938 Lit,
3939 /// Ember and Glimmer components.
3940 Ember,
3941}
3942
3943/// Stable component binding identity, independent of transient parser symbols.
3944#[derive(Debug, Clone, PartialEq, Eq, Hash, bitcode::Encode, bitcode::Decode)]
3945pub enum ComponentReference {
3946 /// A same-module declaration, including resolved immutable local aliases.
3947 Local {
3948 /// Declaration binding name.
3949 name: String,
3950 /// Start byte of the declaration binding.
3951 span_start: u32,
3952 },
3953 /// An import binding. Analysis resolves its effective export via the graph.
3954 Import {
3955 /// Local name of the actual import binding, never a shadowing identifier.
3956 local: String,
3957 /// Start byte of the import binding declaration.
3958 span_start: u32,
3959 },
3960 /// A direct member of a proven namespace import.
3961 NamespaceMember {
3962 /// Local namespace import binding name.
3963 local: String,
3964 /// Namespace import binding byte anchor.
3965 span_start: u32,
3966 /// Effective value export requested by the member access.
3967 member: String,
3968 },
3969 /// A statically registered Angular selector or custom-element tag.
3970 Selector(String),
3971 /// Dynamic or unsupported component identity.
3972 Unknown,
3973}
3974
3975/// A declared public input, kept distinct from legacy unused-prop facts.
3976#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3977pub struct ComponentPropDeclaration {
3978 /// Component declaration name. Empty denotes the sole SFC default export.
3979 pub component: String,
3980 /// Stable declaration binding byte anchor.
3981 pub component_span: u32,
3982 /// Public input name.
3983 pub name: String,
3984 /// Local binding name used by destructured template reads.
3985 pub local: String,
3986 /// Additional public attribute names supplying the same input.
3987 pub aliases: Vec<String>,
3988 /// Declaration byte anchor in the original source.
3989 pub span_start: u32,
3990 /// Whether the declaration explicitly permits omission.
3991 pub optional: bool,
3992 /// Whether omission has a syntactically declared default value.
3993 pub has_default: bool,
3994 /// Whether the input is consumed within the component.
3995 pub is_used: bool,
3996 /// Producer framework.
3997 pub framework: ComponentFramework,
3998 /// Unsupported declarations, forwarding, or open consumers prohibit absence claims.
3999 pub incomplete: bool,
4000}
4001
4002/// One inspected render invocation and its supplied input names.
4003#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
4004pub struct ComponentInvocation {
4005 /// Binding or selector used by the invocation.
4006 pub target: ComponentReference,
4007 /// Original source byte anchor of the opening tag or call.
4008 pub span_start: u32,
4009 /// Supplied names, independent of values and including proven spread keys.
4010 pub supplied: Vec<String>,
4011 /// Case-sensitive Lit JavaScript property bindings, distinct from HTML attributes.
4012 pub supplied_properties: Vec<String>,
4013 /// A spread or dynamic attribute may supply additional names.
4014 pub unknown_props: bool,
4015 /// Framework syntax of this caller.
4016 pub framework: ComponentFramework,
4017}
4018
4019/// Persisted syntactic evidence for conservative component-input analysis.
4020#[derive(Debug, Clone, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
4021pub struct ComponentContractFacts {
4022 /// Immutable root script aliases resolved to their semantic targets.
4023 pub aliases: Vec<ComponentAliasBinding>,
4024 /// Exact Angular templateUrl source owned by each component binding.
4025 pub external_templates: Vec<ComponentExternalTemplate>,
4026 /// Original component bodies that own embedded Glimmer templates.
4027 pub template_owners: Vec<ComponentTemplateOwner>,
4028 /// Effective local export bindings retained after graph payload release.
4029 pub exports: Vec<ComponentExportBinding>,
4030 /// Immutable local object shapes retained for template spread resolution.
4031 pub spread_bindings: Vec<ComponentSpreadBinding>,
4032 /// Known declaration contracts.
4033 pub declarations: Vec<ComponentPropDeclaration>,
4034 /// Inspected render sites, including module-level invocations.
4035 pub invocations: Vec<ComponentInvocation>,
4036 /// Component bindings used opaquely outside inspected renders.
4037 pub escapes: Vec<ComponentReference>,
4038 /// Frameworks with a dynamic consumer whose affected target is unknowable.
4039 pub incomplete_frameworks: Vec<ComponentFramework>,
4040}
4041
4042/// An immutable, unescaped local object with statically known own keys.
4043#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
4044pub struct ComponentSpreadBinding {
4045 /// Root script binding name, resolved before template scopes are applied.
4046 pub local: String,
4047 /// Script binding declaration anchor.
4048 pub span_start: u32,
4049 /// Complete own property names.
4050 pub keys: Vec<String>,
4051}
4052
4053/// An export name resolved to its syntactic component or import binding.
4054#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
4055pub struct ComponentExportBinding {
4056 /// Public export name, including `default`.
4057 pub export_name: String,
4058 /// Original export declaration byte anchor.
4059 pub export_span: u32,
4060 /// Proven local binding, canonicalizing immutable aliases.
4061 pub target: ComponentReference,
4062}
4063
4064/// A semantic component declaration body containing an embedded template.
4065#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
4066pub struct ComponentTemplateOwner {
4067 /// Owning component binding anchor.
4068 pub component_span: u32,
4069 /// Original class body start.
4070 pub start: u32,
4071 /// Original class body end.
4072 pub end: u32,
4073}
4074
4075/// A statically declared external template owned by one component.
4076#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
4077pub struct ComponentExternalTemplate {
4078 /// Owning component binding anchor.
4079 pub component_span: u32,
4080 /// Literal templateUrl source, resolved through the graph import edge.
4081 pub source: String,
4082}
4083
4084/// An immutable root binding that aliases a component or import.
4085#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
4086pub struct ComponentAliasBinding {
4087 /// Root script binding spelling used by template expressions.
4088 pub local: String,
4089 /// Canonical semantic binding target, including its source anchor.
4090 pub target: ComponentReference,
4091}