npm package: @nats-ms/cli
Description: CLI tool for creating and managing NATS microservices
Author: TechnoFrog
Latest version: 0.2.0

# @nats-ms/cli

🚀 CLI tool for creating and managing type-safe NATS microservices with TypeScript.

## Installation

### Global Installation (Recommended)

```bash
npm install -g @nats-ms/cli
```

After installation, the `nats-ms` command will be available globally.

### One-time Use

```bash
npx @nats-ms/cli init my-service
```

## Quick Start

```bash
# 1. Create a new service
nats-ms init user-service

# 2. Navigate to the project
cd user-service

# 3. Install dependencies
npm install

# 4. Run in development mode
npm run dev
```

## Commands

### `nats-ms init <name>`

Initialize a new NATS microservice project with TypeScript and type-safe ServiceMap.

```bash
nats-ms init user-service
```

**Creates:**
- ✅ Full TypeScript configuration
- ✅ ServiceMap with type-safe request/response
- ✅ Example service with handler
- ✅ Auto-discovery enabled by default
- ✅ Development scripts (dev, build, start)
- ✅ Environment configuration
- ✅ README and documentation

### `nats-ms generate-service <name>`

Generate a new service from templates.

```bash
nats-ms generate-service auth --type basic
```

**Options:**
- `-t, --type <type>` - Service type: `basic`, `auth`, or `worker` (default: `basic`)

### `nats-ms dev`

Start development mode with hot reload.

```bash
nats-ms dev
```

**Options:**
- `--no-watch` - Disable file watching
- `-p, --port <port>` - Port number (default: 3000)

### `nats-ms install-manager`

Install and start the frontend manager dashboard for monitoring services.

```bash
nats-ms install-manager
```

**Options:**
- `-p, --port <port>` - Port number for manager (default: 3000)
- `--no-install` - Skip installation, just start
- `--no-start` - Install but do not start

## Generated Project Structure

```
my-service/
├── src/
│   ├── index.ts          # Main service file
│   └── service-map.ts    # Type-safe ServiceMap
├── package.json
├── tsconfig.json
├── .env.example
├── .gitignore
└── README.md
```

## Type-Safe ServiceMap Example

The generated `service-map.ts`:

```typescript
import { ServiceMap } from '@nats-ms/core';
import { z } from 'zod';

export class MyServiceServiceMap extends ServiceMap {
  services = {
    'user.create': {
      request: z.object({
        username: z.string(),
        email: z.string().email(),
      }),
      response: z.object({
        userId: z.string(),
        username: z.string(),
      }),
    },
  } as const;
}
```

## Handler with Automatic Type Inference

In `index.ts`, handlers automatically get typed based on ServiceMap:

```typescript
// ✅ NO need to specify types - they're inferred automatically!
instance.subscribe('user.create', async (req) => {
  const { username, email } = req.data; // ✅ Fully typed from ServiceMap
  
  // TypeScript validates the response matches ServiceMap
  return {
    userId: generateId(),
    username,
  };
});
```

**Important:** Don't add type annotations like `req: MSRequest` - let TypeScript infer types from ServiceMap automatically!

## Features

- 🚀 **Quick scaffolding** - Generate microservice projects in seconds
- 📘 **TypeScript-first** - Full type safety with automatic type inference
- 🔍 **Auto-discovery** - Services automatically announce themselves
- 🎯 **Type-safe** - Request/response types inferred from ServiceMap
- 🛠️ **Dev tools** - Hot reload, monitoring dashboard, and more
- ⚡ **Zero config** - Works out of the box with sensible defaults

## Environment Variables

Generated projects support:

- `NATS_URL` - NATS server URL (default: `nats://localhost:4222`)
- `LOG_LEVEL` - Logging level (default: `info`)

## Development Workflow

### 1. Create Service

```bash
nats-ms init payment-service
cd payment-service
npm install
```

### 2. Define ServiceMap

Edit `src/service-map.ts`:

```typescript
export class PaymentServiceServiceMap extends ServiceMap {
  services = {
    'payment.process': {
      request: z.object({
        orderId: z.string(),
        amount: z.number(),
        currency: z.string(),
      }),
      response: z.object({
        paymentId: z.string(),
        status: z.enum(['success', 'failed']),
      }),
    },
  } as const;
}
```

### 3. Implement Handlers

Edit `src/index.ts`:

```typescript
// Types are automatically inferred!
instance.subscribe('payment.process', async (req) => {
  const { orderId, amount, currency } = req.data;
  
  // Process payment logic...
  
  return {
    paymentId: generatePaymentId(),
    status: 'success',
  };
});
```

### 4. Run & Test

```bash
npm run dev
```

## Scripts in Generated Project

- `npm run dev` - Start with ts-node (hot reload)
- `npm run build` - Build TypeScript to JavaScript
- `npm start` - Run compiled JavaScript

## Requirements

- Node.js >= 18.0.0
- NATS Server (for runtime)

## Related Packages

- [`@nats-ms/core`](https://www.npmjs.com/package/@nats-ms/core) - Core NATS microservices library with type-safe messaging

## Links

- [GitHub Repository](https://github.com/techno-frog/nats-ms)
- [npm Package](https://www.npmjs.com/package/@nats-ms/cli)
- [Core Library](https://www.npmjs.com/package/@nats-ms/core)

## License

MIT © 2025 TechnoFrog LLC