# @botonic/nx-plugin

Nx **generators** and **migrations** for Botonic bot apps and workspaces on the **current** `@botonic/*` line.

## Source and versions

| Line        | npm   | Source                                                           |
| ----------- | ----- | ---------------------------------------------------------------- |
| **Legacy**  | `0.x` | [github.com/hubtype/botonic](https://github.com/hubtype/botonic) |
| **Current** | `2.x` | Hubtype internal monorepo (not public; packages publish to npm)  |

Keep this package aligned in **major version** with `@botonic/core` and other `@botonic/*` dependencies in your workspace.

## Features

- **Bot App Generator**: Creates modern Botonic bot applications with current best practices
- **Migration Tools**: Automatically modernizes legacy Botonic bots to use current patterns
- **Local runtime (no Docker)**: Run and test against the real backend using an external Lambda URL (e.g. ngrok) — see [External developer workflow](docs/external-developer-local-runtime-workflow.md)

## Installation

```bash
pnpm add @botonic/nx-plugin
# or
npm install @botonic/nx-plugin
```

## Generators

### Bot App Generator

Creates a new Botonic bot application with modern patterns:

```bash
nx g @botonic/nx-plugin:bot-app my-bot
```

#### What it creates:

- **Modern Actions**: Async functions using `BotonicContext` instead of React class components
- **React 18 Webchat**: Uses `@botonic/webchat` with `createRoot` and `StrictMode`
- **Current Dependencies**: Uses modern Botonic packages and avoids legacy packages
- **Custom Messages Structure**: Empty structure ready for your custom components

## Migrations

### Upgrade to Nx 23

`@botonic/nx-plugin@2.36.0` requires Nx 23 and no longer supports Nx 22. To upgrade an existing workspace:

```bash
nx migrate @botonic/nx-plugin@2.36.0
pnpm install
nx migrate --run-migrations
```

The migration updates the root `package.json` and each Botonic bot app's `package.json`. It only changes `nx` and `@nx/*` dependencies below major 23.

### Modernize Bot Actions

This migration automatically updates legacy Botonic bots to use current patterns and technologies.

#### Running the Migration

**Interactive project selection (recommended):**

```bash
nx migrate @botonic/nx-plugin
```

When you have multiple bot projects, the migration will show an interactive prompt:

```
📦 Found 3 Botonic bot project(s)
🎯 Select which projects to modernize:

❯ ◯ customer-support-bot (needs migration)
  ◯ sales-bot (already modern)
  ◯ legacy-bot (needs migration)
```

Use arrow keys to navigate, spacebar to select/unselect, and Enter to confirm.

**Migrate all bot projects (non-interactive):**

```bash
# For single project workspaces or automated scripts
nx migrate @botonic/nx-plugin --run-migrations
```

**Migrate specific projects (command line):**

```bash
# Using generator with specific projects
nx g @botonic/nx-plugin:modernize-bot-actions --projects=my-bot,another-bot

# Or using migration file directly
nx migrate @botonic/nx-plugin --run-migrations=migration.json
```

**Project naming:**

- You can use project names with or without the `apps/` prefix
- `my-bot` and `apps/my-bot` are equivalent
- Invalid projects will be rejected with helpful error messages

**Examples:**

```bash
# Migrate a single project
nx g @botonic/nx-plugin:modernize-bot-actions --projects=customer-support-bot

# Migrate multiple specific projects
nx g @botonic/nx-plugin:modernize-bot-actions --projects=bot-1,bot-2,bot-3

# Interactive selection (when multiple projects exist)
nx migrate @botonic/nx-plugin
```

#### Automatic Migration on Upgrade

The migration will automatically run when you upgrade the package:

```bash
# Upgrade will prompt for pending migrations
pnpm add @botonic/nx-plugin@latest
nx migrate @botonic/nx-plugin --run-migrations
```

#### What migrations do:

Migrations automatically update your Botonic projects to use current patterns, dependencies, and best practices. Each migration:

1. **Code Modernization**:
   - Updates code patterns to use current Botonic APIs
   - Transforms legacy implementations to modern equivalents
   - Maintains existing functionality while improving structure

2. **Dependency Management**:
   - Updates Botonic packages to target versions
   - Ensures compatibility across all dependencies
   - Removes deprecated packages when appropriate

3. **Configuration Updates**:
   - Updates project configuration files
   - Applies current best practices and conventions
   - Maintains backward compatibility where possible

4. **Structure Improvements**:
   - Creates missing files or folders as needed
   - Updates file organization to current standards
   - Ensures projects follow recommended patterns

#### Project Selection Benefits

- **🎯 Interactive Selection**: Visual checkboxes with clear status indicators
- **📊 Smart Detection**: Automatically detects which projects need migration vs already modern
- **🧪 Test Gradually**: Migrate one bot at a time to test changes
- **⚡ Selective Updates**: Only modernize bots that are ready
- **🚫 Avoid Conflicts**: Skip bots with ongoing development
- **🔧 Better Control**: Choose which projects to update in each run
- **💡 Clear Status**: See "(needs migration)" or "(already modern)" labels

#### Example Transformation

**Before (legacy React class component):**

```typescript
import React from 'react'
import { Text } from '@botonic/react'

export class Welcome extends React.Component {
  render() {
    return (
      <Text>
        Hello! I'm your bot 🤖
        <br />
        Welcome to Botonic!
      </Text>
    )
  }
}
```

**After (modern async function):**

```typescript
import { BotonicContext } from '@botonic/core'
import { MessageAction } from '@botonic/shared'

export async function Welcome({ sendMessages }: BotonicContext) {
  await sendMessages([
    {
      type: 'text',
      data: { text: "Hello! I'm your bot 🤖\nWelcome to Botonic!" },
      action: MessageAction.SentByBot,
    },
  ])

  return {
    status: 200,
    response: 'OK',
  }
}
```

#### Reviewing Changes

After running the migration, review what changed:

```bash
git diff
```

The migration is **idempotent** - it's safe to run multiple times and will only transform files that need updating.

#### Manual Testing

Run the included test to verify migration functionality:

```bash
# From the plugin directory
pnpm run test:migration
```

This test creates sample legacy bots and verifies the migration transforms them correctly, including project selection functionality.

#### Version Management

The migration is tied to the package version. When you upgrade `@botonic/nx-plugin`, Nx will automatically prompt you to run any new migrations:

```bash
# Check for available migrations
nx migrate @botonic/nx-plugin

# Run pending migrations
nx migrate --run-migrations
```

## Troubleshooting

### Migration Issues

1. **Backup your code** before running migrations (or ensure you have git)
2. **Review changes** with `git diff` after migration
3. **Test your bot** after migration to ensure functionality
4. **Check action logic** for any custom implementations that may need manual updates

### Common Issues

- **Custom action logic**: If your actions have complex business logic, you may need to manually adapt the async function pattern
- **Custom messages**: The migration creates an empty custom messages structure - add your existing custom components
- **Environment variables**: Ensure `VITE_HUBTYPE_APP_ID` is set for the modernized webchat
- **Invalid projects**: If you specify invalid project names, the migration will list available bot projects

### Project Selection

- **Finding projects**: The migration will list all available bot projects if you specify an invalid one
- **Mixed naming**: You can mix project names with and without `apps/` prefix in the same command
- **Non-bot projects**: Projects without Botonic bot structure are automatically ignored

### Safe Migration

Migrations are designed to be safe:

- **Idempotent**: Safe to run multiple times
- **Conservative**: Only transforms known legacy patterns
- **Preserves functionality**: Maintains the same bot behavior
- **Project validation**: Validates project names before making changes

## Contributing

Contributions are handled **inside Hubtype** (this plugin ships with the private Botonic source tree). Add tests for new generators or migrations and follow your team’s internal PR process.

## License

MIT
