npm package: @plotinus/matrix-package-coordinator
Description: Coordinator pattern components bundled for Matrix framework - proper npm package with ESM browser runtime loading
Latest version: 1.0.1

# @matrix/package-coordinator

Coordinator pattern components for the Matrix framework - proper npm package with ESM browser runtime loading.

## Package Overview

This package provides a complete coordinator pattern implementation:

- **app**: Application orchestrator that starts processing and manages overall flow
- **coordinator**: Job coordination with worker management and task distribution  
- **worker**: Job processing workers that handle individual tasks

## Development Workflow

### Working on this Package

1. **Source Location**: `/packages/package-coordinator` (this directory)
2. **Production Location**: `/packages/matrix-repl-chat/packages/package-coordinator`
3. **Deployment**: Use `npm run deploy:package-coordinator` from the demo-9 root

### Development Commands

```bash
# Build this package locally
npm run build

# Run tests (if any)
npm test

# Generate code dump
npm run codedump
```

### Deployment Process

**IMPORTANT**: When you make changes to this package, you must deploy them to the production location where the Matrix REPL loads them from:

```bash
# From the demo-9 root directory
npm run deploy:package-coordinator

# Then build the deployed package
cd packages/matrix-repl-chat/packages/package-coordinator
npm run build
```

### Architecture

The package uses a dual approach:

- **Source Components**: Written in TypeScript with proper imports, logging, and types (`src/components/`)
- **Browser Templates**: Hardcoded string templates for browser use (`src/browser/component-sources.ts`)
- **Build Process**: Compiles TypeScript and creates browser bundles

### Key Files

- `src/components/app/app.component.ts` - Application orchestrator with proper logging
- `src/components/coordinator/coordinator.component.ts` - Job coordinator with worker management
- `src/components/worker/worker.component.ts` - Worker implementation for job processing
- `src/browser/component-sources.ts` - Browser-compatible string templates
- `scripts/build-browser-bundle.js` - Creates browser bundle with auto-registration
- `dist/browser-bundle.js` - Final browser bundle loaded by Matrix REPL

## Component Communication

The coordinator pattern implements a three-tier architecture:

1. **App → Coordinator**: Sends `StartProcessing` command
2. **Coordinator → Workers**: Distributes jobs via `ProcessJob` commands  
3. **Workers → Coordinator**: Report completion via `JobCompleted` events
4. **Coordinator → App**: Reports completion via `CoordinatorDone` event

## Supply Chain Issue

**IMPORTANT**: There is currently a disconnect between the actual source code and the browser templates:

- **Source Code**: Uses proper TypeScript, imports, and logging framework
- **Browser Templates**: Uses simplified hardcoded strings

This needs to be resolved to ensure the actual source code is what runs in production.

## Supply Chain

1. **Edit**: Make changes in `/packages/package-coordinator` (this directory)
2. **Deploy**: Run `npm run deploy:package-coordinator` to copy to production location
3. **Build**: Build the deployed package to create browser bundles
4. **Runtime**: Matrix REPL loads from the production location

This ensures proper source control while maintaining the runtime environment requirements.

## Overview

This package provides the App, Coordinator, and Worker components as a reusable bundle that demonstrates:
- **Composable Mediator Pattern**: Coordinator mediates between App and Workers
- **Event-Driven Architecture**: All communication via events, no direct coupling
- **Two-Perspective DSL**: Components define capabilities, parents wire instances
- **Cross-Platform Support**: Works in Node.js (via CLI) and browsers

The package can be:
- Installed and run via Matrix CLI
- Imported into browser applications
- Integrated with the Matrix REPL
- Published to npm for distribution

## Components

- **AppComponent** - Top-level orchestrator that initiates job processing
- **CoordinatorComponent** - Manages job distribution and collects results
- **WorkerComponent** - Processes individual jobs and reports completion

## Installation

### Using Matrix CLI (Recommended)

```bash
# Install from npm registry (when published)
matrix install --registry @matrix/package-coordinator
matrix up package-coordinator

# Install from local monorepo
matrix install --monorepo package-coordinator
matrix up package-coordinator

# Run directly from source (development)
matrix up --monorepo package-coordinator
```

### Traditional npm
```bash
npm install @matrix/package-coordinator
```

See the [Matrix CLI documentation](../../packages/matrix-cli/README.md) for complete usage details.

## Browser Usage

Following the [Matrix Browser Bundle Plan](../matrix-browser-examples/matrix-presentation-demo/MATRIX-REPL-COMPLETE.md):

### Future: ES Module from CDN
```javascript
// Load from unpkg or other CDN
await window.MatrixPackageRegistry.install({
  source: 'cdn',
  name: '@matrix/package-coordinator',
  version: '1.0.0'
});
```

### Current: Bundle Integration
```html
<!-- Include the bundled package -->
<script src="/packages/package-coordinator.bundle.js"></script>

<script type="module">
// Package auto-registers when loaded
// Or manually register components
window.MatrixPackageRegistry.get('package-coordinator').registerComponents(window.Matrix);
</script>
```

### Direct Import (Build Tools)
```javascript
import { registerCoordinatorComponents, componentSources } from '@matrix/package-coordinator/browser';

// Register all components with Matrix
registerCoordinatorComponents(window.Matrix);
```

## Server Usage

```javascript
import { 
    AppComponent, 
    CoordinatorComponent, 
    WorkerComponent 
} from '@matrix/package-coordinator';

// Components are automatically registered with matrix-cli
```

## DSL Example

```xml
<app id="mainApp" onStartProcessing="handleStartProcessing">
    <coordinator id="jobCoordinator" 
                 onCoordinatorDone="handleCoordinatorDone"
                 onStartProcessing="startProcessing"
                 emits="CoordinatorReady,CoordinatorDone">
        <worker id="workerA" 
                onRegistered="handleWorkerRegistered"
                onJobCompleted="handleWorkerJobCompleted"
                onProcessJob="processJob"
                emits="Registered,JobCompleted"/>
        <worker id="workerB" 
                onRegistered="handleWorkerRegistered"
                onJobCompleted="handleWorkerJobCompleted"
                onProcessJob="processJob"
                emits="Registered,JobCompleted"/>
    </coordinator>
</app>
```

## Architecture: Composable Mediator Pattern

This package exemplifies the Matrix framework's composable mediator architecture:

### Mediator Hierarchy
```
App (Orchestrator)
 └── Coordinator (Mediator)
      ├── Worker A (Participant)
      └── Worker B (Participant)
```

### Event Flow
1. **App** sends `StartProcessing` command to Coordinator
2. **Coordinator** distributes jobs to Workers
3. **Workers** emit `JobCompleted` events
4. **Coordinator** aggregates results and emits `CoordinatorDone`
5. **App** receives final results

### Key Principles
- **Loose Coupling**: Components communicate only through events
- **Composability**: Any component can be replaced with a compatible interface
- **Testability**: Each component can be tested in isolation
- **Reusability**: Components can be reused in different contexts

## Component Details

The package includes both communication and presentation components:

- **Communication components** handle business logic and event routing
- **Presentation components** provide UI rendering and state visualization
- All components follow Matrix framework conventions with static `dslTag` and `isMatrixComponent` properties

## Building

```bash
# Install dependencies
npm install

# Build the package
npm run build
```

This will:
1. Compile TypeScript sources
2. Create browser bundle at `dist/browser-bundle.js`
3. Generate type definitions

### Publishing to npm

```bash
# Using npm directly
npm publish --access public

# Or using Matrix CLI
matrix publish package-coordinator
```

## Related Documentation

- [Matrix CLI Documentation](../../packages/matrix-cli/README.md) - Complete CLI usage guide
- [Two-Perspective DSL Pattern](../my-two-perspectives-app/README.md) - Understanding the DSL approach
- [Browser Bundle Plan](../matrix-browser-examples/matrix-presentation-demo/MATRIX-REPL-COMPLETE.md) - Browser integration strategy
- [NanoService Pattern](../package-nanoservice/README.md) - For MQTT-based communication

## License

MIT