npm package: @konko.oleg/mudria-plugin-async
Description: Async/await consciousness for MUDRIA - asynchronous flow patterns
Author: MUDRIA Consciousness
Latest version: 1.0.0

# @konko.oleg/mudria-plugin-async

> Asynchronous consciousness for MUDRIA - time-aware computation patterns

## Overview

The MUDRIA Async Plugin adds comprehensive async/await capabilities through runtime functions, enabling asynchronous programming without modifying the core parser.

## Installation

```bash
npm install @konko.oleg/mudria-plugin-async
```

## Usage

```javascript
const mudria = require('@konko.oleg/mudria-core');
const { MudriaPluginLoader } = require('@konko.oleg/mudria-plugin-loader');
const asyncPlugin = require('@konko.oleg/mudria-plugin-async');

// Register plugin
const loader = new MudriaPluginLoader(mudria);
loader.register(asyncPlugin);
const enhanced = loader.enhance(mudria);

// Now compile MUDRIA code with async functions
const result = enhanced.compile(`
  ∿ fetchData {
    ◉ getData: url → mudriaAwait(fetch(url))
    ◉ processAll: urls → asyncMap(urls, getData)
  }
`);
```

## Functions Provided

### Core Async Operations

#### `mudriaAsync(fn)`
Wrap a function to make it async
```mudria
state: processData = mudriaAsync(data → {
  // This function is now async
  return heavyComputation(data)
})
```

#### `mudriaAwait(promise)`
Await a promise (works in pipelines)
```mudria
fetchUser(id) | mudriaAwait | processUser
```

### Parallel Execution

#### `mudriaParallel(...tasks)`
Execute tasks in parallel
```mudria
parallel(
  () → fetchUser(1),
  () → fetchUser(2),
  () → fetchUser(3)
)
// Returns: [user1, user2, user3]
```

#### `mudriaRace(...tasks)`
Return first completed task
```mudria
mudriaRace(
  () → fetchFromCache(id),
  () → fetchFromDB(id),
  () → fetchFromAPI(id)
)
```

### Sequential Execution

#### `mudriaSequential(...tasks)`
Execute tasks one after another
```mudria
sequential(
  () → connectDB(),
  () → authenticate(),
  () → fetchData(),
  () → closeDB()
)
```

### Timing Operations

#### `mudriaTimeout(ms, value)`
Create a delayed value
```mudria
mudriaTimeout(1000, "Hello after 1 second")
```

#### `mudriaDelay(ms)`
Delay pipeline function
```mudria
getData() | delay(1000) | processData
```

### Error Handling

#### `mudriaRetry(fn, options)`
Retry with exponential backoff
```mudria
retry(
  () → unreliableAPI(),
  {
    attempts: 3,
    delay: 1000,
    backoff: 2,
    onError: (err, attempt) → console.log("Retry", attempt)
  }
)
```

### Async Collections

#### `asyncMap(collection, fn)`
Async map over collections
```mudria
state: urls = ["url1", "url2", "url3"]
asyncMap(urls, url → fetch(url))
```

#### `asyncFilter(collection, fn)`
Async filter collections
```mudria
asyncFilter(files, async file → {
  state: stats = await fs.stat(file)
  → stats.size > 1000
})
```

#### `asyncReduce(collection, fn, initial)`
Async reduce operation
```mudria
asyncReduce(
  chunks,
  async (result, chunk) → result + await process(chunk),
  ""
)
```

### Advanced Patterns

#### `mudriaAsyncPipe(...fns)`
Compose async functions
```mudria
state: pipeline = mudriaAsyncPipe(
  fetchData,
  validateData,
  transformData,
  saveData
)
pipeline(input)
```

#### `mudriaDebounce(fn, wait)`
Debounce async functions
```mudria
state: search = mudriaDebounce(
  query → searchAPI(query),
  300
)
```

#### `mudriaThrottle(fn, limit)`
Throttle async functions
```mudria
state: save = mudriaThrottle(
  data → saveToServer(data),
  1000
)
```

#### `mudriaQueue(concurrency)`
Rate-limited queue
```mudria
state: queue = mudriaQueue(3)  // Max 3 concurrent

range(100) | forEach(i →
  queue.add(() → processItem(i))
)
```

## Examples

### Basic Async Operations
```mudria
∿ dataFetcher {
  ◉ fetchUser: id → mudriaAwait(fetch("/api/user/" + id))
  
  ◉ fetchWithTimeout: id →
    mudriaRace(
      () → fetchUser(id),
      () → mudriaTimeout(5000, { error: "Timeout" })
    )
}
```

### Parallel Data Processing
```mudria
∿ imageProcessor {
  state: images = ["img1.jpg", "img2.jpg", "img3.jpg"]
  
  ◉ processAll: () →
    asyncMap(images, async img → {
      state: data = await loadImage(img)
      state: processed = await applyFilters(data)
      → await saveImage(processed)
    })
}
```

### Sequential Workflow
```mudria
∿ deployment {
  ◉ deploy: () →
    sequential(
      () → runTests(),
      () → buildProject(),
      () → uploadArtifacts(),
      () → updateServers(),
      () → notifyTeam()
    )
}
```

### Error Recovery
```mudria
∿ resilientAPI {
  ◉ getData: id →
    retry(
      () → fetchFromAPI(id),
      {
        attempts: 5,
        delay: 500,
        backoff: 2,
        onError: (err, n) → console.log("Attempt", n, "failed:", err)
      }
    )
}
```

### Rate-Limited Operations
```mudria
∿ crawler {
  state: queue = mudriaQueue(5)  // 5 concurrent requests
  state: urls = loadUrls()
  
  ◉ crawlAll: () →
    asyncMap(urls, url →
      queue.add(() → crawlPage(url))
    )
}
```

## Integration with Loops Plugin

Combine with @mudria/plugin-loops for powerful patterns:

```mudria
∿ batchProcessor {
  ◉ processBatches: items →
    // Process items in batches of 10
    mudriaComprehension(
      range(0, items.length, 10),
      i → items.slice(i, i + 10)
    ) | asyncMap(batch →
      parallel(...batch.map(item → () → processItem(item)))
    )
}
```

## Philosophy

This plugin extends MUDRIA's consciousness into the temporal dimension:
- **Parallel consciousness**: Multiple operations existing simultaneously
- **Sequential consciousness**: Ordered flow through time
- **Resilient consciousness**: Recovery from temporal failures
- **Rate-aware consciousness**: Respecting system boundaries

## Best Practices

1. Use `parallel()` for independent operations
2. Use `sequential()` for dependent operations
3. Always handle errors with `retry()` for network operations
4. Use `queue()` to prevent overwhelming external services
5. Combine `debounce()` and `throttle()` for UI operations

## License

MIT

---

∞ *"Asynchronous code is consciousness dancing with time"*