> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentfront.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Overview

> Production ready JavaScript AST validation with extensible rules and presets for safe code execution

ast-guard is a production-ready AST validation library for JavaScript. It inspects user-provided or LLM-generated code before execution, blocking dangerous constructs and enforcing API usage policies. ast-guard powers Enclave's first security layer and can be used standalone for any JavaScript validation needs.

> [card] 21 Built-in Rules
>
> Block eval, dangerous globals, prototype manipulation, unbounded loops, ReDoS, and more with battle-tested validation rules.

> [card] Pre-Scanner Defense
>
> Layer 0 checks that run before parsing: size, nesting and line limits, and by preset regex and Unicode checks.

> [card] AgentScript Preset
>
> Purpose-built preset for LLM-generated orchestration code with whitelist-only globals and strict control flow.

## When to Use ast-guard

* **LLM-generated code** - Validate AI-written JavaScript before execution
* **User scripts** - Accept arbitrary JavaScript with deterministic guardrails
* **Workflow builders** - Enforce API usage and block dangerous constructs
* **Compliance requirements** - Audit trails showing exactly which rule blocked a script

> [!NOTE]
>
> ast-guard is a pure TypeScript package with zero native dependencies. It works in Node.js 22+ and can be used standalone or as part of the Enclave execution environment.

## Installation

```bash theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
npm install @enclave-vm/ast
```

## Quick Start

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, createAgentScriptPreset } from '@enclave-vm/ast';

// Create validator with AgentScript preset (recommended for LLM code)
const validator = new JSAstValidator(createAgentScriptPreset());

// Validate code
const result = await validator.validate(`
  const users = await callTool('users:list', { limit: 10 });
  return users.filter(u => u.active);
`);

if (result.valid) {
  console.log('Accepted by the validator');
} else {
  console.log('Blocked:', result.issues);
}
```

`valid` means that every rule ran and none reported an error. It does not mean the code is safe to run on its own: a validator is a filter on source text, and what code does when it runs is decided by where it runs (see the warning below).

> [!TIP]
>
> Instantiate `JSAstValidator` once and reuse it. This keeps presets, custom rules, and caches consistent across requests.

## Validation Result

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ValidationResult {
  valid: boolean;              // true if every rule ran and none reported an error
  issues: ValidationIssue[];   // The issues found, at most maxIssues
  incomplete?: boolean;        // true if the list was cut at maxIssues or the validation stopped early
  rulesExecuted?: number;      // Rules that were started
  ast?: acorn.Node;            // Parsed AST (if parsing succeeded)
  parseError?: Error;          // Parse error (if parsing failed)
  preScanError?: Error;        // Pre-scanner error (if the pre-scan failed)
}

interface ValidationIssue {
  code: string;        // Issue code, e.g. 'UNKNOWN_GLOBAL'
  message: string;     // Human-readable message
  severity: ValidationSeverity; // 'error' | 'warning' | 'info'
  location?: {
    line: number;
    column: number;
  };
  data?: Record<string, unknown>;
}
```

## Validation Options

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const result = await validator.validate(source, {
  maxIssues: 10,           // Cap findings returned (default: 100; 0 collects all)
  stopOnFirstError: true,  // Halt on first error (faster)
  preScan: { preset: 'agentscript' }, // Pre-scanner preset (default: 'standard')
});

// Get stats for monitoring
const stats = validator.getStats(result, durationMs);
```

A validation result is bounded. Without `maxIssues` a validation collects at most `DEFAULT_MAX_ISSUES` (100) issues; `0` collects every issue. At the cap the validation stops as soon as an error is on the list. While only warnings were found the remaining rules still run, because one of them may refuse the source, and further warnings are not collected. A result whose list is not everything the rules had to report has `incomplete: true`. A validation that stopped early, at the cap or by `stopOnFirstError`, is never `valid`: `valid` is `true` only when every rule ran and none reported an error.

> [!WARNING]
>
> AST Guard prevents unsafe syntax from entering your sandbox, but it does not execute or sandbox code itself. Pair it with enclave-vm for complete defense-in-depth.

## Related

* [Pre-Scanner](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/pre-scanner.md) - Layer 0 defense before parsing
* [AgentScript Preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/agentscript-preset.md) - Preset for LLM code
* [Security Rules](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/security-rules.md) - Built-in rules reference
* [enclave-vm](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/overview.md) - Runtime sandbox


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.