# Archify Live Preview Mode Architecture: How It Works Under the Hood

> Explore Archify live preview mode architecture. Learn how it validates JSON diagrams and updates HTML previews only on successful compilation, ensuring a stable user experience.

- Repository: [tt-a1i/archify](https://github.com/tt-a1i/archify)
- Tags: architecture
- Published: 2026-08-31

---

**Archify's live preview mode continuously watches a JSON diagram file, validates every change through the full compile pipeline, and updates an HTML preview only when the new candidate passes all validation gates—falling back to the last-known-good diagram on any failure.**

Archify is an open-source diagram-as-code tool that generates interactive visualizations from JSON definitions. Its live preview mode is a desktop-only feature designed to give developers instant feedback while editing diagrams. This article examines the complete architecture behind this feature, tracing how the file watcher, validation pipeline, and HTML preview server work together to maintain a stable, always-working preview.

## The Three-Core Component Architecture

Archify's live preview consists of three tightly coupled components that orchestrate the edit-compile-preview cycle.

### File-Watcher Daemon

The watcher runs a Node.js loop using `fs.watch` to monitor the target JSON file for changes. It is initialized by the CLI when you pass the `--watch` or `--live-preview` flag.

In `archify/bin/archify.mjs` (lines ≈1080‑1145), the daemon starts the watcher and handles critical error states like "Could not load live preview." The watcher operates entirely locally—no network operations are involved in the file monitoring itself, which keeps latency near zero.

### Validation Pipeline

Every detected change is piped through Archify's standard compilation process:

1. **Schema validation** – ensures the JSON conforms to the Archify schema
2. **Linting** – checks for common errors and style issues
3. **Dependency resolution** – links external resources and nested diagrams

The live-preview code reuses the `compile` API from the core library—this is the same pipeline invoked by `archify build`. The result is either a **candidate** diagram ready for preview or a **failure** with diagnostic information.

### HTML Preview Server

When validation succeeds, the server:

- Writes the compiled HTML bundle to a temporary folder
- Serves it via a tiny HTTP server bound to loopback only (`127.0.0.1`)
- Refreshes an `<iframe>` in the client page to display the updated diagram

The server logic resides in `archify/bin/archify.mjs`, while the front-end UI is defined in [`scripts/gallery-template.html`](https://github.com/tt-a1i/archify/blob/main/scripts/gallery-template.html). This template includes a **"Preview: dark/light"** toggle that swaps the CSS theme without triggering a rebuild.

## Last-Known-Good Fallback Mechanism

The defining safety feature of Archify's live preview mode is its **last-good fallback** behavior.

When a candidate fails any validation gate, the server **does not** replace the currently served HTML. The preview continues showing the most recent successful build. This is implemented by preserving the previous bundle on disk and only overwriting it after a successful compile.

This contract is explicitly tested in `preview-contract.test.mjs`, which verifies that:
- Live preview is desktop-only
- The fallback behavior is explicit and automatic
- Users never see broken or partially-rendered diagrams

The `repository-evidence.test.mjs` test demonstrates how live preview forwards repository roots and only publishes verified evidence, reinforcing this "last-good" guarantee at the architectural level.

## Security and Sandboxing

The preview server is intentionally constrained to prevent security risks:

- **Loopback-only binding** – verified in `open-artifact.test.mjs`, the server refuses external connections
- **No authentication required** – local-only access eliminates credential management
- **Plain HTML output** – no external services or APIs are contacted

These constraints make the live preview mode safe to run in any development environment without network configuration.

## Starting and Using Live Preview

### CLI Usage

Start watching a diagram file with automatic browser preview:

```bash

# Watch my-diagram.json and open the preview

archify --watch my-diagram.json

# Equivalent long-form flag

archify --live-preview my-diagram.json

```

### Programmatic API

Integrate live preview into custom tooling:

```javascript
import { compile } from '@archify/core';
import { startLivePreview } from '@archify/preview';

// Start a watch loop with success callback
await startLivePreview({
  entry: 'my-diagram.json',
  onSuccess: html => console.log('Preview updated!'),
});

```

### Theme Toggling in the UI

The generated preview page exposes a theme switcher that operates client-side:

```javascript
// From scripts/gallery-template.html
document.getElementById('preview-theme')
        .addEventListener('click', () => {
  const next = previewTheme === 'dark' ? 'light' : 'dark';
  applyPreviewTheme(next);
});

```

This avoids a full recompile when switching between dark and light modes.

## Key Implementation Files

| File | Purpose |
|------|---------|
| `archify/bin/archify.mjs` | CLI entry point with watcher initialization, error handling, and HTTP server logic |
| `archify/test/preview-contract.test.mjs` | Contract tests defining desktop-only behavior and last-good guarantees |
| `archify/test/open-artifact.test.mjs` | Verifies loopback-only server binding for sandboxed operation |
| [`scripts/gallery-template.html`](https://github.com/tt-a1i/archify/blob/main/scripts/gallery-template.html) | Preview UI template with `<iframe>` renderer and theme toggle |
| `archify/test/repository-evidence.test.mjs` | Tests repository root forwarding and verified evidence publishing |

## Summary

- **Archify live preview mode** combines a Node.js file watcher, the standard `compile` API, and a loopback HTTP server for instant diagram feedback
- **Validation gates** block broken updates—only verified candidates reach the preview
- **Last-known-good fallback** preserves the previous successful build when edits fail
- **Desktop-only, no-external-dependencies design** ensures speed, simplicity, and security
- Core implementation spans `archify.mjs` for orchestration and [`gallery-template.html`](https://github.com/tt-a1i/archify/blob/main/gallery-template.html) for presentation

## Frequently Asked Questions

### Why does Archify's live preview only work on desktop?

The file watcher relies on Node.js `fs.watch`, which requires a local filesystem. The architecture explicitly excludes remote or containerized environments where file watching would be unreliable. This constraint is enforced by the CLI and verified in `preview-contract.test.mjs`.

### What happens if I save invalid JSON while live preview is running?

The preview **does not update**. The server discards the failed compile and continues serving the last successful build. You can see validation errors in the terminal, but the browser preview remains stable showing your most recent working diagram.

### Can I use live preview without installing the full Archify CLI?

No. The watcher and server are integrated into `archify/bin/archify.mjs`. However, you can import `@archify/preview` programmatically—`startLivePreview()` still requires the core compilation libraries as peers.

### How do I change the preview theme without rebuilding?

Click the **"Preview: dark/light"** toggle in the UI. The theme swap applies CSS classes client-side via `applyPreviewTheme()` in [`scripts/gallery-template.html`](https://github.com/tt-a1i/archify/blob/main/scripts/gallery-template.html). No recompile is triggered because the diagram structure remains unchanged.