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