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