Skip to main content

fallow_output/
coverage_envelopes.rs

1//! Coverage command output envelopes.
2
3use crate::RuntimeCoverageReport;
4use crate::root_envelopes::{attach_telemetry_meta, serialize_named_json_output};
5use fallow_types::envelope::{ElapsedMs, Meta, ToolVersion};
6use serde::Serialize;
7use std::time::Duration;
8
9/// `fallow coverage setup --json` envelope.
10#[derive(Debug, Clone, Serialize)]
11#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
12#[cfg_attr(feature = "schema", schemars(title = "fallow coverage setup --json"))]
13pub struct CoverageSetupOutput {
14    /// Setup output schema version; serialized as the string `"1"`.
15    pub schema_version: CoverageSetupSchemaVersion,
16    /// Framework detected at the project root.
17    pub framework_detected: CoverageSetupFramework,
18    /// Package manager detected from lockfiles, when one was found.
19    pub package_manager: Option<CoverageSetupPackageManager>,
20    /// Runtimes the instrumentation must cover at the project root.
21    pub runtime_targets: Vec<CoverageSetupRuntimeTarget>,
22    /// Per-member setup guidance for workspace projects.
23    pub members: Vec<CoverageSetupMember>,
24    /// Coverage config that was written to disk, when setup wrote one.
25    pub config_written: Option<serde_json::Value>,
26    /// Shell commands the user should run to complete setup.
27    pub commands: Vec<String>,
28    /// Files the user must edit by hand, with reasons.
29    pub files_to_edit: Vec<CoverageSetupFileToEdit>,
30    /// Ready-to-paste code snippets for the files to edit.
31    pub snippets: Vec<CoverageSetupSnippet>,
32    /// Dockerfile additions needed for containerized capture, when relevant.
33    pub dockerfile_snippet: Option<String>,
34    /// Ordered human-readable follow-up instructions.
35    pub next_steps: Vec<String>,
36    /// Non-fatal problems encountered during detection.
37    pub warnings: Vec<String>,
38    /// Fallow Cloud plan, present only for `fallow coverage setup --cloud`.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub cloud: Option<CoverageSetupCloud>,
41    /// `_meta` block with docs and field definitions, when requested.
42    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
43    pub meta: Option<serde_json::Value>,
44}
45
46/// Fallow Cloud plan of `fallow coverage setup --cloud`.
47///
48/// The beacon, the inventory, the source maps and the deployment registration
49/// must all carry the same commit SHA. The plan names only the environment
50/// variable names of keys, never a key value.
51#[derive(Debug, Clone, Serialize)]
52#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
53pub struct CoverageSetupCloud {
54    /// Fallow Cloud project id (`owner/repo`), or null when it was not detected.
55    pub project_id: Option<String>,
56    /// Commit SHA that `--wait` checks: `--git-sha`, else `HEAD` of the
57    /// working tree, or null outside a git repository.
58    pub git_sha: Option<String>,
59    /// Fallow Cloud API base URL.
60    pub endpoint: String,
61    /// Environment variable that holds the full API key in CI and on the server.
62    pub api_key_env: String,
63    /// Environment variable that holds the ingest-only browser key, when a
64    /// member runs in the browser.
65    pub browser_key_env: Option<String>,
66    /// Environment variables the server snippets read the deployed commit SHA
67    /// from, in order.
68    pub commit_sha_env: Vec<String>,
69    /// CI steps that upload the inventory and source maps and register the
70    /// deployment.
71    pub ci: CoverageSetupCi,
72    /// Whether the production build needs a source map upload.
73    pub source_maps: CoverageSetupSourceMaps,
74    /// Activation endpoint that reports each setup step, or null without a
75    /// project id.
76    pub activation_url: Option<String>,
77    /// Command that waits until the cloud reports every step as done.
78    pub wait_command: String,
79    /// Result of `--wait`, present only when the command waited.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub wait: Option<CoverageSetupWait>,
82}
83
84/// CI provider of a Fallow Cloud setup plan.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
86#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
87#[serde(rename_all = "snake_case")]
88pub enum CoverageSetupCiProvider {
89    /// GitHub Actions workflow steps.
90    GithubActions,
91}
92
93/// CI steps of a Fallow Cloud setup plan.
94#[derive(Debug, Clone, Serialize)]
95#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
96pub struct CoverageSetupCi {
97    /// CI provider the steps are written for.
98    pub provider: CoverageSetupCiProvider,
99    /// Existing workflow files that look like a deploy workflow, relative to
100    /// the project root.
101    pub workflows_detected: Vec<String>,
102    /// Workflow steps to add to the job that builds and deploys.
103    pub steps: String,
104    /// Where the steps go and what they need.
105    pub instructions: String,
106}
107
108/// Source map guidance of a Fallow Cloud setup plan.
109#[derive(Debug, Clone, Serialize)]
110#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
111pub struct CoverageSetupSourceMaps {
112    /// Whether the CI steps upload source maps.
113    pub needed: bool,
114    /// Build output directories the maps are uploaded from, one per bundled
115    /// workspace member, relative to the project root. Empty when no upload
116    /// is needed.
117    pub dirs: Vec<String>,
118    /// Why the upload is or is not needed.
119    pub reason: String,
120}
121
122/// Outcome of `fallow coverage setup --cloud --wait`.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
124#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
125#[serde(rename_all = "snake_case")]
126pub enum CoverageSetupWaitOutcome {
127    /// The cloud reported every step as done.
128    Complete,
129    /// The wait timed out before every step was done.
130    Timeout,
131    /// The activation endpoint could not be read.
132    Error,
133}
134
135/// Result of `fallow coverage setup --cloud --wait`.
136#[derive(Debug, Clone, Serialize)]
137#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
138pub struct CoverageSetupWait {
139    /// How the wait ended.
140    pub outcome: CoverageSetupWaitOutcome,
141    /// The last activation response body (`data`) from the cloud, unchanged,
142    /// or null when no read succeeded. New step ids and states can appear.
143    pub activation: Option<serde_json::Value>,
144    /// Error text when the outcome is `error`.
145    pub message: Option<String>,
146}
147
148/// Schema-version discriminator for [`CoverageSetupOutput`].
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
150#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
151pub enum CoverageSetupSchemaVersion {
152    /// First release of the coverage setup format.
153    #[serde(rename = "1")]
154    V1,
155}
156
157/// Framework detected during coverage setup; drives which instrumentation
158/// guidance is emitted.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
160#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
161#[serde(rename_all = "snake_case")]
162pub enum CoverageSetupFramework {
163    /// Next.js application.
164    #[serde(rename = "nextjs")]
165    NextJs,
166    /// NestJS application.
167    #[serde(rename = "nestjs")]
168    NestJs,
169    /// Nuxt application.
170    Nuxt,
171    /// SvelteKit application.
172    #[serde(rename = "sveltekit")]
173    SvelteKit,
174    /// Astro application.
175    Astro,
176    /// Remix application.
177    Remix,
178    /// Vite-built application without a detected meta-framework.
179    Vite,
180    /// Node project without a detected framework or bundler.
181    PlainNode,
182    /// No framework signal was found.
183    Unknown,
184}
185
186/// Package manager detected from the project's lockfile.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
188#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
189#[serde(rename_all = "lowercase")]
190pub enum CoverageSetupPackageManager {
191    /// npm (`package-lock.json`).
192    Npm,
193    /// pnpm (`pnpm-lock.yaml`).
194    Pnpm,
195    /// Yarn (`yarn.lock`).
196    Yarn,
197    /// Bun (`bun.lock` / `bun.lockb`).
198    Bun,
199}
200
201/// Runtime environment coverage capture must instrument.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
203#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
204#[serde(rename_all = "lowercase")]
205pub enum CoverageSetupRuntimeTarget {
206    /// Server-side Node.js execution.
207    Node,
208    /// Client-side browser execution.
209    Browser,
210}
211
212/// Per-workspace-member setup guidance inside [`CoverageSetupOutput::members`].
213#[derive(Debug, Clone, Serialize)]
214#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
215pub struct CoverageSetupMember {
216    /// Package name of the workspace member.
217    pub name: String,
218    /// Member path relative to the workspace root.
219    pub path: String,
220    /// Framework detected for this member.
221    pub framework_detected: CoverageSetupFramework,
222    /// Package manager detected for this member, when one was found.
223    pub package_manager: Option<CoverageSetupPackageManager>,
224    /// Runtimes the instrumentation must cover for this member.
225    pub runtime_targets: Vec<CoverageSetupRuntimeTarget>,
226    /// Files the user must edit by hand, with reasons.
227    pub files_to_edit: Vec<CoverageSetupFileToEdit>,
228    /// Ready-to-paste code snippets for the files to edit.
229    pub snippets: Vec<CoverageSetupSnippet>,
230    /// Dockerfile additions needed for containerized capture, when relevant.
231    pub dockerfile_snippet: Option<String>,
232    /// Non-fatal problems encountered during detection.
233    pub warnings: Vec<String>,
234}
235
236/// One manual edit the user must make to wire up coverage capture.
237#[derive(Debug, Clone, Serialize)]
238#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
239pub struct CoverageSetupFileToEdit {
240    /// File path relative to the project root.
241    pub path: String,
242    /// Why the file needs editing.
243    pub reason: String,
244}
245
246/// Ready-to-paste code snippet accompanying a file edit.
247#[derive(Debug, Clone, Serialize)]
248#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
249pub struct CoverageSetupSnippet {
250    /// Short description of what the snippet does.
251    pub label: String,
252    /// File path the snippet belongs in.
253    pub path: String,
254    /// The snippet source text.
255    pub content: String,
256}
257
258/// Schema-version discriminator for [`CoverageAnalyzeOutput`].
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
260#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
261pub enum CoverageAnalyzeSchemaVersion {
262    /// First release of the coverage analyze format.
263    #[serde(rename = "1")]
264    V1,
265    /// Expands the required semantic omission reason-code enum.
266    #[serde(rename = "2")]
267    V2,
268    /// Makes the runtime summary totals `functions_tracked`, `functions_unhit`
269    /// and `coverage_percent` nullable (null for a positive-only capture) and
270    /// adds `summary.capture_policy`.
271    #[serde(rename = "3")]
272    V3,
273}
274
275/// Envelope emitted by `fallow coverage analyze --format json`.
276#[derive(Debug, Clone, Serialize)]
277#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
278#[cfg_attr(
279    feature = "schema",
280    schemars(title = "fallow coverage analyze --format json")
281)]
282pub struct CoverageAnalyzeOutput {
283    /// Analyze output schema version; currently serialized as the string `"2"`.
284    pub schema_version: CoverageAnalyzeSchemaVersion,
285    /// Fallow CLI version that produced this output.
286    pub version: ToolVersion,
287    /// Wall-clock analysis duration in milliseconds.
288    pub elapsed_ms: ElapsedMs,
289    /// Runtime-coverage report body.
290    pub runtime_coverage: RuntimeCoverageReport,
291    /// `_meta` block. A `--format json` run of the CLI always sets
292    /// `telemetry.analysis_run_id`. With `--explain`, it also holds the docs
293    /// URL and the metric definitions.
294    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
295    pub meta: Option<Meta>,
296}
297
298/// Serialize the `fallow coverage setup --json` envelope.
299///
300/// # Errors
301///
302/// Returns a serde error when the envelope cannot be converted to JSON.
303pub fn serialize_coverage_setup_json_output(
304    output: CoverageSetupOutput,
305    analysis_run_id: Option<&str>,
306) -> Result<serde_json::Value, serde_json::Error> {
307    let mut value = serialize_named_json_output(output, "coverage-setup")?;
308    attach_telemetry_meta(&mut value, analysis_run_id);
309    Ok(value)
310}
311
312/// Build the `fallow coverage analyze --format json` envelope.
313#[must_use]
314pub fn build_coverage_analyze_output(
315    report: &RuntimeCoverageReport,
316    elapsed: Duration,
317    version: impl Into<String>,
318) -> CoverageAnalyzeOutput {
319    CoverageAnalyzeOutput {
320        schema_version: CoverageAnalyzeSchemaVersion::V3,
321        version: ToolVersion(version.into()),
322        elapsed_ms: ElapsedMs(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)),
323        runtime_coverage: report.clone(),
324        meta: None,
325    }
326}
327
328/// Serialize the `fallow coverage analyze --format json` envelope.
329///
330/// `explain_meta` is inserted after typed-envelope serialization because the
331/// existing command metadata is a JSON object shared with docs/schema helpers.
332///
333/// # Errors
334///
335/// Returns a serde error when the envelope cannot be converted to JSON.
336pub fn serialize_coverage_analyze_json_output(
337    output: CoverageAnalyzeOutput,
338    explain_meta: Option<serde_json::Value>,
339    analysis_run_id: Option<&str>,
340) -> Result<serde_json::Value, serde_json::Error> {
341    let mut value = serialize_named_json_output(output, "coverage-analyze")?;
342    if let Some(meta) = explain_meta
343        && let Some(map) = value.as_object_mut()
344    {
345        map.insert("_meta".to_owned(), meta);
346    }
347    attach_telemetry_meta(&mut value, analysis_run_id);
348    Ok(value)
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354    use serde_json::json;
355
356    #[test]
357    fn coverage_setup_json_output_uses_named_root_contract() {
358        let output = CoverageSetupOutput {
359            schema_version: CoverageSetupSchemaVersion::V1,
360            framework_detected: CoverageSetupFramework::Unknown,
361            package_manager: None,
362            runtime_targets: Vec::new(),
363            members: Vec::new(),
364            config_written: None,
365            commands: Vec::new(),
366            files_to_edit: Vec::new(),
367            snippets: Vec::new(),
368            dockerfile_snippet: None,
369            next_steps: Vec::new(),
370            warnings: Vec::new(),
371            cloud: None,
372            meta: None,
373        };
374
375        let value = serialize_coverage_setup_json_output(output, Some("run-1"))
376            .expect("coverage setup should serialize");
377
378        assert_eq!(value["kind"], "coverage-setup");
379        assert_eq!(value["schema_version"], "1");
380        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-1");
381    }
382
383    #[test]
384    fn coverage_analyze_json_output_inserts_explain_meta_and_telemetry() {
385        let report = RuntimeCoverageReport::default();
386        let output = build_coverage_analyze_output(&report, Duration::from_millis(7), "test");
387
388        let value = serialize_coverage_analyze_json_output(
389            output,
390            Some(json!({"docs": "coverage"})),
391            Some("run-2"),
392        )
393        .expect("coverage analyze should serialize");
394
395        assert_eq!(value["kind"], "coverage-analyze");
396        assert_eq!(value["schema_version"], "3");
397        assert_eq!(value["elapsed_ms"], 7);
398        assert_eq!(value["_meta"]["docs"], "coverage");
399        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-2");
400    }
401}