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