node-app-build 6.12.0

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! `node-app audit` — run the embedded blueprint's auditable patterns
//! against a project on disk. Soft mode (default) only warns; --strict
//! flips warnings to hard errors.
//!
//! Phase 1 of econ-v1/node#868 introduced the audit harness with three of
//! four patterns implemented (the other two stubbed with OK notes).
//! Phase 5a of #868 (this PR) tightens packaging:
//!   - `NoWholesaleNodeModulesWhenBundled` becomes an ERROR when the app
//!     pins `manifest.nodeApp.blueprint: ">=2"`. Apps pinned at v1 keep
//!     the warning for one release cycle.
//!   - `PrivateNativeDepsInPrivateModulesDir` (new) cross-checks that
//!     packages declared in `nodeApp.privateRuntime` are actually resolvable
//!     for staging under `private_modules/`.

use crate::blueprint::{Pattern, APP_SDK_MEMORY_REPORTING_FLOOR, CURRENT};
use anyhow::Result;
use serde::Serialize;
use std::path::Path;

#[derive(Debug, Serialize)]
struct Finding {
    pattern: String,
    severity: Severity,
    message: String,
    fix: Option<String>,
}

#[derive(Debug, Serialize, PartialEq)]
enum Severity {
    Ok,
    Warning,
    Error,
}

pub fn run(path: &Path, strict: bool, json: bool) -> Result<()> {
    let mut findings = Vec::new();

    let manifest_path = path.join("manifest.json");
    let manifest = if manifest_path.exists() {
        let raw = std::fs::read_to_string(&manifest_path)?;
        Some(serde_json::from_str::<serde_json::Value>(&raw)?)
    } else {
        findings.push(Finding {
            pattern: "manifest_present".into(),
            severity: Severity::Error,
            message: "manifest.json missing".into(),
            fix: Some(
                "run `node-app new` to scaffold, or hand-write a manifest.json".into(),
            ),
        });
        None
    };

    // app_type — surface shared-runtime fitness up-front
    if let Some(m) = &manifest {
        match m.get("app_type").and_then(|v| v.as_str()) {
            Some("bun") => findings.push(Finding {
                pattern: "app_type_check".into(),
                severity: Severity::Ok,
                message: "app_type=bun (eligible for shared runtime — set shared_runtime_enabled per-app at install time)".into(),
                fix: None,
            }),
            Some("native") => findings.push(Finding {
                pattern: "app_type_check".into(),
                severity: Severity::Ok,
                message: "app_type=native (cdylib, loaded in-process; shared runtime does not apply)".into(),
                fix: None,
            }),
            Some("standalone") => findings.push(Finding {
                pattern: "app_type_check".into(),
                severity: Severity::Warning,
                message: "app_type=standalone — own systemd unit; shared runtime memory savings do NOT apply".into(),
                fix: Some(
                    "if you don't strictly need own-systemd-unit semantics, consider `app_type: bun` instead".into(),
                ),
            }),
            other => findings.push(Finding {
                pattern: "app_type_check".into(),
                severity: Severity::Error,
                message: format!("manifest.app_type unrecognized: {:?}", other),
                fix: Some("use one of: bun, native, standalone".into()),
            }),
        }
    }

    // Resolve the app's declared blueprint pin (manifest.nodeApp.blueprint).
    // Defaults to ">=1" — apps that haven't opted into v2 yet keep the
    // v1 warning behavior for one release cycle.
    let pinned_min = pinned_min_blueprint(manifest.as_ref());

    // Implement each Pattern from CURRENT.patterns:
    for pattern in CURRENT.patterns {
        let f = match pattern {
            Pattern::NoWholesaleNodeModulesWhenBundled => {
                check_no_wholesale_node_modules(path, pinned_min)
            }
            Pattern::SharedExternalsMatchPin => {
                check_shared_externals_match_pin(path, manifest.as_ref())
            }
            Pattern::PrivateNativeDepsDeclared => {
                check_private_native_deps_declared(path, manifest.as_ref())
            }
            Pattern::NoBunBuildCompileForBunApps => {
                check_no_bun_compile_for_bun_apps(path, manifest.as_ref())
            }
            Pattern::PrivateNativeDepsInPrivateModulesDir => {
                check_private_native_deps_in_private_modules(path, manifest.as_ref())
            }
            Pattern::BunAppSdkReportsMemory => {
                check_bun_app_sdk_reports_memory(path, manifest.as_ref())
            }
        };
        if let Some(f) = f {
            findings.push(f);
        }
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&findings)?);
    } else {
        for f in &findings {
            let icon = match f.severity {
                Severity::Ok => "",
                Severity::Warning => "",
                Severity::Error => "",
            };
            println!("{} {}{}", icon, f.pattern, f.message);
            if let Some(fix) = &f.fix {
                println!("    fix: {}", fix);
            }
        }
    }

    let has_errors = findings.iter().any(|f| f.severity == Severity::Error);
    let has_warnings = findings.iter().any(|f| f.severity == Severity::Warning);
    if has_errors || (strict && has_warnings) {
        std::process::exit(1);
    }
    Ok(())
}

/// Severity for `NoWholesaleNodeModulesWhenBundled` depends on the
/// blueprint version the app pins (manifest.nodeApp.blueprint):
///   - `>=1` (or unset): warning. Backward-compat for one release cycle.
///   - `>=2` (or higher): hard error. Apps that have opted into v2 MUST
///     keep the wholesale node_modules/ out of the .deb (use
///     `nodeApp.privateRuntime` to declare native deps instead).
fn check_no_wholesale_node_modules(path: &Path, pinned_min: u32) -> Option<Finding> {
    let dist = path.join("dist/index.js");
    let nm = path.join("node_modules");
    if !(dist.exists() && nm.exists()) {
        return None;
    }
    let severity = if pinned_min >= 2 {
        Severity::Error
    } else {
        Severity::Warning
    };
    let message = if pinned_min >= 2 {
        "dist/index.js present alongside `node_modules/`; blueprint v2 forbids staging wholesale node_modules/ in the .deb".to_string()
    } else {
        "dist/index.js present but `node_modules/` would be staged in the .deb (allowed under blueprint v1; tightens to error at v2)".to_string()
    };
    Some(Finding {
        pattern: "NoWholesaleNodeModulesWhenBundled".into(),
        severity,
        message,
        fix: Some(
            "list native runtime deps under manifest.nodeApp.privateRuntime and pin manifest.nodeApp.blueprint: \">=2\" — `node-app package` then stages private_modules/<pkg> only".into(),
        ),
    })
}

fn check_shared_externals_match_pin(
    path: &Path,
    _manifest: Option<&serde_json::Value>,
) -> Option<Finding> {
    // Stub for phase 1 — defer the actual version-match logic to phase 6.
    // For now just print informational reminder that the shared-deps lint
    // (infra/scripts/lint-shared-deps.mjs) is the source of truth.
    let pkg = path.join("package.json");
    if !pkg.exists() {
        return None;
    }
    Some(Finding {
        pattern: "SharedExternalsMatchPin".into(),
        severity: Severity::Ok,
        message: "shared-deps version-pin checked via infra/scripts/lint-shared-deps.mjs (deferred to phase 6)".into(),
        fix: None,
    })
}

fn check_private_native_deps_declared(
    path: &Path,
    manifest: Option<&serde_json::Value>,
) -> Option<Finding> {
    // Stub for phase 1 — checking which deps have native bindings is non-trivial
    // (need to walk node_modules and look for .node files / binding.gyp). Defer
    // the real check to phase 4. For now, an OK note.
    let _ = (path, manifest);
    Some(Finding {
        pattern: "PrivateNativeDepsDeclared".into(),
        severity: Severity::Ok,
        message: "private-native-deps audit deferred to phase 4 — declare them manually in manifest.json#nodeApp.privateRuntime for now".into(),
        fix: None,
    })
}

fn check_no_bun_compile_for_bun_apps(
    path: &Path,
    manifest: Option<&serde_json::Value>,
) -> Option<Finding> {
    let app_type = manifest?.get("app_type")?.as_str()?;
    if app_type != "bun" {
        return None;
    }
    let pkg_path = path.join("package.json");
    if !pkg_path.exists() {
        return None;
    }
    let raw = std::fs::read_to_string(&pkg_path).ok()?;
    let pkg: serde_json::Value = serde_json::from_str(&raw).ok()?;
    let scripts = pkg.get("scripts")?.as_object()?;
    for (name, cmd) in scripts {
        if let Some(s) = cmd.as_str() {
            if s.contains("bun build") && s.contains("--compile") {
                return Some(Finding {
                    pattern: "NoBunBuildCompileForBunApps".into(),
                    severity: Severity::Warning,
                    message: format!(
                        "package.json script `{}` uses `bun build --compile` — incompatible with shared runtime",
                        name
                    ),
                    fix: Some(
                        "drop --compile from the build script; ship dist/index.js so the supervisor can spawn it as a Worker".into(),
                    ),
                });
            }
        }
    }
    None
}

/// Cross-check that every package listed in `manifest.nodeApp.privateRuntime`
/// is resolvable at staging time — either present under `node_modules/<pkg>`
/// (so `node-app package` can copy it into `private_modules/<pkg>`) or
/// already pre-staged under `private_modules/<pkg>` in the source tree.
/// No-op when `nodeApp.privateRuntime` is empty/absent.
fn check_private_native_deps_in_private_modules(
    path: &Path,
    manifest: Option<&serde_json::Value>,
) -> Option<Finding> {
    let private_runtime = manifest
        .and_then(|m| m.get("nodeApp"))
        .and_then(|n| n.get("privateRuntime"))
        .and_then(|v| v.as_array());
    let pkgs: Vec<&str> = {
        let arr = private_runtime?;
        arr.iter().filter_map(|v| v.as_str()).collect()
    };
    if pkgs.is_empty() {
        return None;
    }

    let dist = path.join("dist/index.js");
    if !dist.exists() {
        // No staging artifact yet to cross-check against; this lint only
        // fires once `node-app build` has produced dist/.
        return Some(Finding {
            pattern: "PrivateNativeDepsInPrivateModulesDir".into(),
            severity: Severity::Ok,
            message: format!(
                "{} private runtime pkg(s) declared; run `node-app build` then re-audit to cross-check staging",
                pkgs.len()
            ),
            fix: None,
        });
    }

    let mut missing: Vec<&str> = Vec::new();
    for pkg in &pkgs {
        let in_node_modules = path.join("node_modules").join(pkg).exists();
        let in_private_modules = path.join("private_modules").join(pkg).exists();
        if !in_node_modules && !in_private_modules {
            missing.push(pkg);
        }
    }
    if missing.is_empty() {
        Some(Finding {
            pattern: "PrivateNativeDepsInPrivateModulesDir".into(),
            severity: Severity::Ok,
            message: format!(
                "all {} declared private runtime pkg(s) resolvable for staging: {}",
                pkgs.len(),
                pkgs.join(", ")
            ),
            fix: None,
        })
    } else {
        Some(Finding {
            pattern: "PrivateNativeDepsInPrivateModulesDir".into(),
            severity: Severity::Error,
            message: format!(
                "manifest.nodeApp.privateRuntime declares pkg(s) not on disk: {}",
                missing.join(", ")
            ),
            fix: Some(
                "run `bun install` so node_modules/<pkg>/ exists; or remove the unused entries from manifest.nodeApp.privateRuntime".into(),
            ),
        })
    }
}

/// Lowest version a npm range can resolve to, for the simple range shapes
/// that actually appear in these manifests: an exact pin (`6.9.4`), a caret
/// or tilde (`^6.9.4`, `~6.9.4`), or a comparator (`>=6.9.0`, `=6.9.4`).
///
/// Deliberately conservative: anything it cannot parse returns `None` and the
/// caller reports "could not determine" rather than guessing a verdict. A
/// wrong PASS here would be worse than no check at all.
fn min_version_of_range(range: &str) -> Option<(u64, u64, u64)> {
    let trimmed = range.trim().trim_start_matches(['^', '~', '=', '>', '<', 'v']).trim();
    // Drop any pre-release/build suffix (`6.9.0-rc.1` -> `6.9.0`) and split.
    let core = trimmed
        .split(['-', '+', ' ', ','])
        .next()?
        .trim();
    let mut parts = core.split('.');
    let major = parts.next()?.parse::<u64>().ok()?;
    // A partial range (`6`, `6.9`) can resolve no lower than `.0`.
    let minor = parts.next().map_or(Some(0), |p| p.parse::<u64>().ok())?;
    let patch = parts.next().map_or(Some(0), |p| p.parse::<u64>().ok())?;
    Some((major, minor, patch))
}

/// `app_type: "bun"` apps must pin an `@econ-v1/app-sdk` at or above
/// [`APP_SDK_MEMORY_REPORTING_FLOOR`], or the host can never attribute their
/// memory. See the `Pattern::BunAppSdkReportsMemory` doc comment for why this
/// reports at `Severity::Ok` today instead of warning.
fn check_bun_app_sdk_reports_memory(
    path: &Path,
    manifest: Option<&serde_json::Value>,
) -> Option<Finding> {
    if manifest?.get("app_type")?.as_str()? != "bun" {
        return None;
    }
    let pkg_path = path.join("package.json");
    if !pkg_path.exists() {
        return None;
    }
    let raw = std::fs::read_to_string(&pkg_path).ok()?;
    let pkg: serde_json::Value = serde_json::from_str(&raw).ok()?;
    let declared = pkg
        .get("dependencies")
        .and_then(|d| d.get("@econ-v1/app-sdk"))
        .and_then(|v| v.as_str());

    let (floor_major, floor_minor, floor_patch) = APP_SDK_MEMORY_REPORTING_FLOOR;
    let floor = format!("{floor_major}.{floor_minor}.{floor_patch}");

    let Some(range) = declared else {
        return Some(Finding {
            pattern: "BunAppSdkReportsMemory".into(),
            severity: Severity::Ok,
            message:
                "app_type=bun but package.json declares no @econ-v1/app-sdk dependency — this app \
                 cannot self-report its JS heap, so the host will show it as unattributed"
                    .into(),
            fix: Some(format!(
                "add \"@econ-v1/app-sdk\": \"^{floor}\" to dependencies if this app runs on the SDK lifecycle"
            )),
        });
    };

    let Some(min) = min_version_of_range(range) else {
        return Some(Finding {
            pattern: "BunAppSdkReportsMemory".into(),
            severity: Severity::Ok,
            message: format!(
                "could not determine the lowest @econ-v1/app-sdk version \"{range}\" resolves to; \
                 memory self-reporting needs >= {floor}"
            ),
            fix: None,
        });
    };

    if min >= APP_SDK_MEMORY_REPORTING_FLOOR {
        Some(Finding {
            pattern: "BunAppSdkReportsMemory".into(),
            severity: Severity::Ok,
            message: format!(
                "@econ-v1/app-sdk \"{range}\" is at or above the {floor} memory-reporting floor — \
                 this app self-reports its heap (attribution: exact_isolate)"
            ),
            fix: None,
        })
    } else {
        Some(Finding {
            pattern: "BunAppSdkReportsMemory".into(),
            severity: Severity::Ok,
            message: format!(
                "@econ-v1/app-sdk \"{range}\" is BELOW the {floor} memory-reporting floor — the SDK \
                 never sends app_memory, so this app shows as unattributed in the per-app memory UI"
            ),
            fix: Some(format!(
                "bump the @econ-v1/app-sdk dependency to ^{floor} or newer (the 5.x -> 6.9.x jump is \
                 additive: no exports removed, engines unchanged)"
            )),
        })
    }
}

/// Parse `manifest.nodeApp.blueprint` (e.g. `">=2"`) and return the minimum
/// blueprint version it pins. Unrecognized / missing pin defaults to 1.
fn pinned_min_blueprint(manifest: Option<&serde_json::Value>) -> u32 {
    let s = manifest
        .and_then(|m| m.get("nodeApp"))
        .and_then(|n| n.get("blueprint"))
        .and_then(|v| v.as_str())
        .unwrap_or(">=1");
    // Only `>=N` semantics are honored today; anything else falls back to v1.
    if let Some(rest) = s.strip_prefix(">=") {
        rest.trim().parse::<u32>().unwrap_or(1)
    } else {
        s.trim().parse::<u32>().unwrap_or(1)
    }
}

#[cfg(test)]
mod bun_sdk_memory_floor_tests {
    use super::*;

    fn write_app(dir: &std::path::Path, app_type: &str, sdk: Option<&str>) {
        std::fs::write(
            dir.join("manifest.json"),
            format!(r#"{{"name":"t","version":"1.0.0","app_type":"{app_type}"}}"#),
        )
        .unwrap();
        let deps = match sdk {
            Some(v) => format!(r#"{{"@econ-v1/app-sdk":"{v}"}}"#),
            None => "{}".to_string(),
        };
        std::fs::write(
            dir.join("package.json"),
            format!(r#"{{"name":"t","dependencies":{deps}}}"#),
        )
        .unwrap();
    }

    fn finding_for(app_type: &str, sdk: Option<&str>) -> Option<Finding> {
        let tmp = tempfile::tempdir().unwrap();
        write_app(tmp.path(), app_type, sdk);
        let raw = std::fs::read_to_string(tmp.path().join("manifest.json")).unwrap();
        let manifest: serde_json::Value = serde_json::from_str(&raw).unwrap();
        check_bun_app_sdk_reports_memory(tmp.path(), Some(&manifest))
    }

    #[test]
    fn min_version_handles_the_range_shapes_these_manifests_actually_use() {
        assert_eq!(min_version_of_range("6.9.4"), Some((6, 9, 4)));
        assert_eq!(min_version_of_range("^6.9.4"), Some((6, 9, 4)));
        assert_eq!(min_version_of_range("~6.9.0"), Some((6, 9, 0)));
        assert_eq!(min_version_of_range(">=6.9.0"), Some((6, 9, 0)));
        assert_eq!(min_version_of_range("=5.28.4"), Some((5, 28, 4)));
        // Partial ranges can resolve no lower than `.0`.
        assert_eq!(min_version_of_range("^6"), Some((6, 0, 0)));
        assert_eq!(min_version_of_range("^6.9"), Some((6, 9, 0)));
        // Pre-release suffix is dropped down to its core version.
        assert_eq!(min_version_of_range("6.9.0-rc.1"), Some((6, 9, 0)));
        // Unparseable shapes must NOT be guessed at.
        assert_eq!(min_version_of_range("latest"), None);
        assert_eq!(min_version_of_range("workspace:*"), None);
    }

    #[test]
    fn caret_five_x_is_below_the_floor_even_though_it_floats() {
        // `^5.28.4` floats only within 5.x, so it can never reach 6.9.0 —
        // the exact trap that left every extracted app unattributed.
        let f = finding_for("bun", Some("^5.28.4")).expect("bun app yields a finding");
        assert!(f.message.contains("BELOW"), "got: {}", f.message);
        assert!(f.fix.is_some(), "a below-floor finding must say how to fix it");
    }

    #[test]
    fn at_or_above_the_floor_passes() {
        for range in ["^6.9.0", "6.9.4", "^7.0.0"] {
            let f = finding_for("bun", Some(range)).expect("bun app yields a finding");
            assert!(
                f.message.contains("at or above"),
                "{range} should pass, got: {}",
                f.message
            );
        }
    }

    #[test]
    fn reports_ok_severity_so_strict_releases_do_not_break() {
        // `node-app audit --strict` exits non-zero on warnings too, so this
        // rule must stay informational until the apps are bumped.
        let f = finding_for("bun", Some("^5.28.4")).unwrap();
        assert_eq!(f.severity, Severity::Ok);
    }

    #[test]
    fn non_bun_apps_are_not_audited_for_this() {
        assert!(finding_for("native", Some("^5.28.4")).is_none());
        assert!(finding_for("standalone", None).is_none());
    }

    #[test]
    fn missing_sdk_dependency_is_called_out_rather_than_silently_passing() {
        let f = finding_for("bun", None).expect("a bun app with no SDK dep still yields a finding");
        assert!(f.message.contains("no @econ-v1/app-sdk"), "got: {}", f.message);
    }
}