# probar-js-gen

NASA/DO-178B-grade Rust DSL for type-safe JavaScript generation.

**Zero raw JavaScript. Zero manual editing. Zero defects.**

## Why This Exists

Raw JavaScript strings in Rust codebases are a liability:
1. **No Compiler Checks**: Typos, syntax errors, reserved words pass silently
2. **No Immutability**: Generated files can be manually edited, breaking invariants
3. **No Traceability**: Changes to generated code are undetectable

This crate solves all three with a typed DSL, hash manifests, and property-based testing.

## Features

| Feature | Guarantee | Verification |
|---------|-----------|--------------|
| **Type Safety** | Invalid JS is unrepresentable | Compile-time |
| **Identifier Validation** | Reserved words rejected | Runtime + Tests |
| **Immutability** | Blake3 hash manifests | `verify()` function |
| **Determinism** | Same input = same output | Property tests |
| **No Forbidden Patterns** | window, eval, etc. blocked | Static analysis |

## Quick Start

```rust
use probar_js_gen::prelude::*;

// Build a JavaScript module
let module = JsModuleBuilder::new()
    .comment("Generated by probar-js-gen - DO NOT EDIT")
    .let_decl("x", Expr::num(42))?
    .const_decl("msg", Expr::str("hello"))?
    .build();

// Generate JavaScript code
let js = generate(&module);

// Write with manifest for immutability verification
write_with_manifest(
    Path::new("./output.js"),
    &js,
    GenerationMetadata {
        tool: "my-tool".to_string(),
        version: "1.0.0".to_string(),
        input_hash: "abc123".to_string(),
        timestamp: "2024-01-01T00:00:00Z".to_string(),
        regenerate_cmd: "my-tool gen".to_string(),
    },
)?;

// Later, verify the file wasn't tampered with
verify(Path::new("./output.js"))?;
```

## Toyota Way Principles

This crate implements the Toyota Production System principles for software:

### Jidoka (Automation with Human Touch)
- **Stop the Line**: Any validation failure halts generation immediately
- **Andon**: Error messages include regeneration instructions
- **Poka-Yoke**: Type system prevents invalid constructs

### Genchi Genbutsu (Go and See)
- **No Blind Trust**: All generated code is verified
- **Observable State**: Manifest tracks generation metadata

### Kaizen (Continuous Improvement)
- **Property Tests**: 1000+ random cases per property
- **Mutation Testing**: 85%+ mutation score required

### Yokoten (Horizontal Deployment)
- **Reusable DSL**: Same patterns for Workers, Worklets, any JS context

## Quality Guarantees

| Metric | Minimum | Target |
|--------|---------|--------|
| Test Coverage | 90% | 95% |
| Mutation Score | 85% | 90% |
| Property Tests | 1000 cases/property | 10000 |
| Clippy Warnings | 0 | 0 |
| Doc Coverage | 100% | 100% |

### Run Quality Gates

```bash
# Unit + property tests
cargo test

# Coverage
cargo llvm-cov --html

# Mutation testing
cargo mutants

# Clippy (pedantic)
cargo clippy -- -D warnings
```

## 100-Point Falsification Checklist

See [FALSIFICATION.md](./FALSIFICATION.md) for the complete Popperian falsification checklist.
Each of the 100 claims is:
- **Testable**: Has a concrete test
- **Refutable**: Can be proven false
- **Independent**: Orthogonal to other claims

## Peer-Reviewed References

### Formal Methods
1. McKeeman, W.M. (1998) "Differential Testing for Software", _Digital Technical Journal_
2. Claessen & Hughes (2000) "QuickCheck: A Lightweight Tool for Random Testing", _ICFP_
3. DeMillo et al. (1978) "Hints on Test Data Selection", _IEEE Computer_

### JavaScript Semantics
4. Maffeis et al. (2008) "An Operational Semantics for JavaScript", _APLAS_
5. Guha et al. (2010) "The Essence of JavaScript", _ECOOP_
6. ECMA-262 (ES2022) Specification

### Software Safety
7. Leveson, N.G. (2012) "Engineering a Safer World", MIT Press
8. RTCA DO-178C (2011) "Software Considerations in Airborne Systems"
9. Holzmann, G.J. (2006) "The Power of 10", _IEEE Computer_

### Hash Functions
10. O'Connor et al. (2020) "BLAKE3: One Function, Fast Everywhere", _RWC_

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                         User Code                           │
│                                                             │
│   JsModuleBuilder::new()                                    │
│       .let_decl("x", Expr::num(42))?                       │
│       .build()                                              │
└─────────────────────┬───────────────────────────────────────┘
                      │
                      ▼
┌─────────────────────────────────────────────────────────────┐
│                     HIR (Type-Safe AST)                     │
│                                                             │
│   JsModule { statements: [Stmt::Let { name, value }] }     │
│                                                             │
│   Validation: Identifier::new() rejects reserved words      │
└─────────────────────┬───────────────────────────────────────┘
                      │
                      ▼
┌─────────────────────────────────────────────────────────────┐
│                     Code Generation                         │
│                                                             │
│   generate(&module) → "let x = 42;"                        │
│                                                             │
│   Deterministic: Same HIR → Same output (always)            │
└─────────────────────┬───────────────────────────────────────┘
                      │
                      ▼
┌─────────────────────────────────────────────────────────────┐
│                     Manifest System                         │
│                                                             │
│   write_with_manifest() → output.js + output.js.manifest   │
│   verify() → Err if hash mismatch (file was edited!)       │
│                                                             │
│   Blake3 hash ensures no undetected modifications           │
└─────────────────────────────────────────────────────────────┘
```

## Forbidden Patterns

The validator rejects generated code containing these patterns:

| Pattern | Reason | Context |
|---------|--------|---------|
| `window.` | Workers have no window | Worker |
| `document.` | Workers have no document | Worker |
| `importScripts` | Use dynamic `import()` | Worker |
| `eval(` | Security risk | All |
| `Function(` | Security risk | All |
| `with(` | Deprecated | All |
| `__proto__` | Prototype pollution | All |

## Use Cases

### Web Workers

```rust
let module = JsModuleBuilder::new()
    .comment("Transcription Worker")
    .let_decl("wasm", Expr::null())?
    .stmt(Stmt::on_message(vec![
        // Handle messages from main thread
    ]))
    .build();

let js = generate(&module);
let errors = validator::validate_worker_js(&js);
assert!(errors.is_empty());
```

### AudioWorklets

```rust
let class = JsClassBuilder::new("MyProcessor")?
    .extends("AudioWorkletProcessor")?
    .constructor(vec![])
    .method("process", &["inputs", "outputs", "params"], vec![
        Stmt::ret_val(Expr::bool(true)),
    ])?
    .build();

let module = JsModuleBuilder::new()
    .class(class)
    .register_processor("my-processor", "MyProcessor")?
    .build();

let js = generate(&module);
let errors = validator::validate_worklet_js(&js);
assert!(errors.is_empty());
```

## License

MIT OR Apache-2.0

---

Part of the [Aprender monorepo](https://github.com/paiml/aprender) — 70 workspace crates.
