# Lexicon Client - Claude Code Development Context

## Project Overview

TypeScript-first client library for Lexicon DJ's local REST API. Provides type-safe access to tracks, playlists, tags, and player control with comprehensive error handling using the Result pattern.

## Architecture

### Core Structure

```
src/
├── client/           # API namespace implementations
│   ├── namespaces/   # Individual API modules (tracks, playlists, tags, control)
│   └── base/         # Base client and HTTP utilities
├── types/            # TypeScript type definitions
│   ├── client/       # Client-specific types
│   └── generated.ts  # OpenAPI-generated types
├── schemas/          # Zod validation schemas
│   └── entities/     # Entity schema definitions
└── index.ts          # Main exports
```

### Key Design Patterns

- **Result Pattern**: All API methods return `Result<T, ApiError>` using neverthrow
- **Namespace Organization**: API methods grouped by domain (tracks, playlists, tags, control)
- **Type Safety**: Zod schemas for runtime validation + TypeScript for compile-time safety
- **Unified Client**: Single client instance with lazy-loaded namespaces
- **Recursive Types**: Proper handling of nested playlists with TypeScript inference

## Development Workflow

### Testing Strategy

- **Unit Tests**: `npm run test:unit` - Schema validation, error handling, type inference
- **Integration Tests**: `npm run test:integration` - Real API testing (requires Lexicon DJ)
- **Demo Validation**: `npm run demo:test` - Build verification with React + Node.js

### Build Process

- **TSup Configuration**: Dual ESM/CJS builds with TypeScript declarations
- **Optimization**: Minification, tree-shaking, external dependency handling
- **Verification**: Automated build validation and bundle analysis

### Release Process

- **Changesets**: Semantic versioning with automated changelog generation
- **GitHub Actions**: CI/CD with matrix testing, security scanning, provenance
- **NPM Publishing**: Automated releases with SLSA Level 3 attestation

## Critical Implementation Details

### Schema Typing Issues

The PlaylistSchema uses recursive typing that requires careful TypeScript handling:

```typescript
// CORRECT: Proper recursive typing
export type Playlist = z.infer<typeof BasePlaylistSchema> & {
  playlists?: Playlist[]
}

export const PlaylistSchema: z.ZodType<Playlist> = BasePlaylistSchema.extend({
  playlists: z.lazy(() => z.array(PlaylistSchema)).optional(),
}) as z.ZodType<Playlist>

// WRONG: Breaks TypeScript inference
const PlaylistSchema: z.ZodType<unknown> = ... // This causes type inference failures
```

### Error Handling Pattern

```typescript
// Standard API call pattern
const result = await client.tracks.list({ limit: 25 })
if (result.isOk()) {
  // Type-safe success handling
  const tracks = result.value.tracks
} else {
  // Structured error handling
  console.error(result.error.message)
}
```

### Client Reuse Pattern

```typescript
// React: Single client instance with useMemo
const client = useMemo<LexiconClient>(() => createClient(), [])

// Node.js: Module-level client instance
const client = createClient()
```

## Recent Changes and Context

### Build Optimization

- Updated tsup.config.ts for production-optimized builds
- Added build verification scripts and bundle analysis
- Configured external dependencies to reduce bundle size

### Demo Applications

- **React + Vite**: ESM build validation with interactive UI testing
- **Node.js Script**: CommonJS build validation with comprehensive API testing
- Both demos limit results appropriately (25 tracks, 3 playlists, 5 tags)

### TypeScript Fixes

- Fixed PlaylistSchema recursive typing for proper inference
- Resolved tsconfig incremental build conflicts with tsup
- Updated all type exports for consistent API surface

### CI/CD Implementation

- Comprehensive GitHub Actions workflows with matrix testing
- Changesets integration for automated releases
- Security scanning and NPM provenance attestation
- Removed Codecov per project requirements

## Development Commands

### Core Development

```bash
npm run dev          # Watch mode development
npm run build        # Production build
npm run typecheck    # TypeScript validation
npm run lint         # ESLint checking
npm run test:unit    # Unit test suite
```

### Integration Testing

```bash
npm run lexicon:check           # Verify Lexicon DJ is running
npm run test:integration        # Full integration test suite
npm run test:integration:tracks # Track-specific integration tests
```

### Demo and Validation

```bash
npm run demo:react   # Run React demo (ESM validation)
npm run demo:node    # Run Node.js demo (CJS validation)
npm run demo:test    # Full demo validation workflow
```

### Build Analysis

```bash
npm run build:analyze # Bundle size analysis
npm run build:verify  # Build verification with imports
```

### Release Management

```bash
npm run changeset         # Create new changeset
npm run changeset:status  # Check release status
npm run release          # Publish to NPM (CI only)
```

## API Namespace Details

### Tracks API (`client.tracks`)

- `list(params)` - Paginated track listing with sorting
- `search(params)` - Advanced search with filters and query strings
- `get({ id })` - Single track retrieval
- `getBatch({ ids })` - Batch track operations

### Playlists API (`client.playlists`)

- `list()` - All playlists with hierarchy
- `get({ id, includeTracks? })` - Single playlist with optional track data
- Supports nested playlists with proper TypeScript recursion

### Tags API (`client.tags`)

- `list()` - All tags and categories
- `get({ id })` - Single tag retrieval
- Category support with structured organization

### Control API (`client.control.player`)

- `getCurrentState()` - Current player state and track info
- `play()`, `pause()`, `stop()` - Basic playback controls
- `seek({ progress })` - Seek to position (0-1)
- `setVolume({ level })` - Volume control (0-1)
- `loadTrack({ id })`, `loadPlaylist({ id })` - Content loading

## Dependencies and External Libraries

### Runtime Dependencies

- **zod**: Schema validation and TypeScript inference
- **neverthrow**: Functional error handling with Result pattern
- **undici**: Modern HTTP client for Node.js environments
- **ts-pattern**: Pattern matching for complex type operations
- **pino**: High-performance structured logging
- **p-queue**: Request concurrency management
- **qs**: URL query string serialization

### Development Dependencies

- **tsup**: Build tool with ESM/CJS dual output
- **vitest**: Testing framework with TypeScript support
- **@changesets/cli**: Semantic versioning and release management
- **eslint/prettier**: Code quality and formatting
- **msw**: Mock Service Worker for API mocking in tests

## Testing Approach

### Unit Tests (`src/__tests__/units/`)

- Schema validation and type inference verification
- Error handling scenario testing
- Client instantiation and configuration testing
- Type safety validation for all API methods

### Integration Tests (`src/__tests__/integration/`)

- Real API testing against running Lexicon DJ instance
- Complete workflow validation (search → get → control)
- Error handling with actual API responses
- Performance and reliability testing

### Demo Validation

- ESM build testing in React + Vite environment
- CommonJS build testing in Node.js scripts
- Package installation and import verification
- Cross-platform compatibility validation

## Common Development Tasks

### Adding New API Endpoints

1. Update `src/types/generated.ts` with new OpenAPI schema
2. Add method to appropriate namespace client
3. Create Zod schema in `src/schemas/entities/`
4. Add unit tests for validation and error handling
5. Add integration tests if endpoint requires Lexicon DJ

### Updating Schemas

1. Regenerate types: `npm run generate:types`
2. Update corresponding Zod schemas in `src/schemas/`
3. Run `npm run typecheck` to verify TypeScript compatibility
4. Update unit tests for schema changes

### Release Preparation

1. Run full validation: `npm run validate`
2. Create changeset: `npm run changeset`
3. Build and verify: `npm run build && npm run build:verify`
4. Test demos: `npm run demo:test`
5. Push to GitHub (triggers automated release)

## Important Notes

### Lexicon DJ Requirements

- Must have Lexicon DJ installed and running
- Local API must be enabled in Settings → Integrations
- Default connection: `localhost:48624`
- Integration tests require live Lexicon DJ instance

### Type Safety Considerations

- All API responses use Result pattern for error handling
- Zod schemas provide runtime validation beyond TypeScript
- Recursive types (Playlist) require special TypeScript handling
- Generic type parameters support custom filtering

### Performance Optimizations

- P-queue manages request concurrency
- External dependencies marked in tsup config to reduce bundle size
- Tree-shaking enabled for minimal production builds
- Keep-names preserves function names for debugging

### Security Practices

- No secrets or API keys committed to repository
- NPM provenance attestation for supply chain security
- GitHub security scanning in CI pipeline
- Proper dependency management with audit checks

This library follows TypeScript-first development principles with comprehensive type safety, functional error handling, and production-ready build optimization.
