npm package: @mchen-lab/app-kit
Description: Standard Application Shell for the News Workspace Fleet
Latest version: 0.1.15

# @mchen-lab/app-kit

A standardized Node-centric application shell for the workspace fleet.

## Purpose
Provides a consistent foundation for web services, ensuring standardization across the fleet. It handles:
- **Scaffolding**: Rapidly creating new services with a standard directory structure.
- **Lifecycle Management**: Updating existing services to the latest standards via `app-kit update`.
- **Runtime**: Unified Express server setup with safe defaults (CORS, JSON, Logging).
- **Frontend Integration**: Seamless single-port development with Vite HMR.

## CLI Usage

`app-kit` is designed to be run using `npx`, ensuring you always have the latest templates and logic without needing a global installation.

### 🚀 Creating a New Project (Factory)

To scaffold a new standardized application, run:

```bash
npx @mchen-lab/app-kit create <project-name> [options]
```

**Options:**
- `--port <number>`: Internal port for the service (default: `3000`).
- `--no-frontend`: Create a backend-only service.
- `--vanilla`: Use Vanilla TypeScript instead of React for the frontend.

**Example:**
```bash
npx @mchen-lab/app-kit create my-service --port 8080
```

### 🔄 Updating Managed Files

One of the core strengths of `app-kit` is lifecycle management. You can pull in the latest infrastructure fixes (Dockerfiles, CI scripts, build logic) by running:

```bash
# Run this inside your project root
npx @mchen-lab/app-kit update
```

This will compare your project's "managed files" with the latest templates and update them safely.

## Configuration

### `devops.config.json`
This file is the source of truth for your project's infrastructure configuration. App-Kit uses it to generate `Dockerfile`, CI workflows, and release scripts.

**Example:**
```json
{
  "projectName": "My Service",
  "imageName": "my-service",
  "ghcrOrg": "mchen-lab",
  "ports": [3000]
}
```

### Configuration Merging Priority
App-Kit uses a multi-layered configuration strategy with the following priority (highest to lowest):
1. **UI Configuration / `settings.json`**: Direct edits in the UI have the highest priority.
2. **Environment Variables**: Overrides defaults (e.g., `EXAMPLE_SETTING=value`).
3. **Default Config**: The `defaultConfig` object passed to `createApp`.

### Persistence & Directories
By default, `app-kit` uses a standardized directory structure for data and logs:

- **`DATA_DIR`**: Location for configuration files (defaults to `./data`). Stores `settings.json`.
- **`LOGS_DIR`**: Location for persistent log files (defaults to `./logs`). Stores `app.log`.

You can override these locations using environment variables:
```bash
DATA_DIR=/path/to/data LOGS_DIR=/path/to/logs npm start
```

### Managed Files (⚠️ CAUTION)
App-Kit enforces consistency by "managing" specific files. **Do not edit these files manually**, as they will be overwritten the next time you run `app-kit update`.

Managed files are marked with a header:
```typescript
// ===== AUTO-GENERATED BY APP-KIT - DO NOT EDIT =====
```

**Common Managed Files:**
- `Dockerfile`
- `vite.config.ts`
- `tsconfig.server.json`
- `.github/workflows/ci.yml`
- `restart.sh`
- Valid scripts in `devops/`
- `Dockerfile`
- `vite.config.ts`

## Versioning & Commit Tracking

App-Kit identifies your application's state using three key pieces of information:

1.  **Version**: Read from `package.json`. In production, this is prefixed with `v` and appended with `BUILD_METADATA` (e.g., `v0.1.0-dev-20260128`).
2.  **Commit Hash**: Captured from the host environment during build. 
    - **Development**: Vite attempts to run `git rev-parse --short HEAD`.
    - **Production**: Injected as an `ARG` during Docker build (`GIT_COMMIT`).
3.  **Port**: Dynamically reported by the backend API at runtime.

### ⚠️ Git Requirement
For the **Commit Hash** to be correctly captured, your project **must be a Git repository** with at least one commit. If it is not a git repo, the hash will display as `unknown`.

```bash
# Initialize git if you haven't already
git init
git add .
git commit -m "initial commit"
```

## Local Development

### `restart.sh`
Every App-Kit project comes with a robust `restart.sh` script. Use this for your daily development instead of `npm run dev` directly.

```bash
./restart.sh
```

**What it does:**
1.  **Ensures Clean Port**: Kills any zombies or orphan processes on your configured port.
2.  **Log Management**: Backs up old logs to `*.bak` so you don't lose history.
3.  **Starts Server**: Launches the backend in watch mode (which proxies to Vite for frontend HMR).
4.  **Tails Logs**: Streams the server output to your terminal.

## Runtime Library

For the backend code you write, `app-kit` provides a helper to set up Express with best practices.

```typescript
import { createApp } from "@mchen-lab/app-kit/backend";

const appKit = createApp({
  appName: "My Service",
  // app-kit automatically loads config from 'data/settings.json'
  defaultConfig: { 
    myFeatureEnabled: true 
  }
});

const app = appKit.app; // Configured Express instance

app.get("/api/hello", (req, res) => {
  res.json({ message: "Hello World" });
});

app.listen(3000);
```

#### Real-time & Persistent Logging
App-Kit projects include a robust logging system:
- **Real-time**: Broadcasters events to connected WebSocket clients for UI display.
- **Persistent**: Automatically appends all logs to `${LOGS_DIR}/app.log` for troubleshooting and audits.

#### Backend Testing
App-Kit provides a standardized testing environment for backend logic using Vitest. Run tests using:
```bash
npm test
```
The test runner is configured to look for test files in `src/server/`.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.