npm package: @synet/resolver
Description: Resolve DID documents
Author: Synet Team
Latest version: 1.0.0

# DID Resolver Unit

```bash
  _____                 _                  
 |  __ \               | |                 
 | |__) |___  ___  ___ | |_   _____ _ __   
 |  _  // _ \/ __|/ _ \| \ \ / / _ \ '__|  
 | | \ \  __/\__ \ (_) | |\ V /  __/ |     
 |_|_ \_\___||___/\___/|_| \_/ \___|_|     
   | |  | |     (_) |                      
   | |  | |_ __  _| |_                     
   | |  | | '_ \| | __|                    
   | |__| | | | | | |_                     
    \____/|_| |_|_|\__|                    
                                           
version: 1.0.0      
```

Zero-dependency DID resolver implementing Unit Architecture. Supports `did:key` and `did:web` methods with built-in caching, events, and capability learning for ai agents.

## Installation

```bash
npm install @synet/resolver
```

## Quick Start

```typescript
import { PureDIDResolverUnit } from '@synet/resolver';

const resolver = PureDIDResolverUnit.create();

// Resolve DID documents
const result = await resolver.resolve('did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK');
console.log(result.didDocument);

// Parse DID structure
const parsed = resolver.parse('did:web:example.com');
console.log(parsed.components);
```

## Supported DID Methods

### did:key
Cryptographic identifiers using Ed25519 public keys. Self-contained resolution with no network dependencies.

```typescript
const result = await resolver.resolve('did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK');
```

### did:web
Domain-based identifiers that resolve via HTTPS. Follows W3C DID specification for web-based DID documents.

```typescript
const result = await resolver.resolve('did:web:example.com');
const result = await resolver.resolve('did:web:example.com:users:alice');
```

## Configuration

```typescript
const resolver = PureDIDResolverUnit.create({
  enableCache: true,        // Enable response caching
  enableEvents: true,       // Enable event emission
  cacheSize: 1000,         // Maximum cache entries
  timeout: 5000            // HTTP timeout in milliseconds
});
```

## Caching

Built-in LRU cache for resolved DID documents:

```typescript
// Cache is enabled by default
const result1 = await resolver.resolve(did); // Network call
const result2 = await resolver.resolve(did); // From cache

// Clear cache
resolver.clearCache();

// Get cache statistics
const stats = resolver.getStats();
console.log(stats.cacheHitRate);
```

## Events

Monitor DID resolution operations:

```typescript
resolver.on('did.resolve.success', (event) => {
  console.log(`Resolved ${event.did} in ${event.duration}ms`);
});

resolver.on('did.resolve.error', (event) => {
  console.log(`Failed to resolve ${event.did}: ${event.errorMsg}`);
});

resolver.on('did.parse.success', (event) => {
  console.log(`Parsed ${event.did} as ${event.method} method`);
});
```

## Unit Architecture

This resolver implements Unit Architecture patterns:

### Teaching Capabilities
```typescript
const teaching = resolver.teach();
// Returns: { unitId, capabilities, schema, validator }

// Other units can learn from this resolver
otherUnit.learn([teaching]);
```

### Learning Capabilities
```typescript
// Resolver can learn from other units
const cryptoUnit = CryptoUnit.create();
resolver.learn([cryptoUnit.teach()]);

// Now has crypto capabilities
if (resolver.can('crypto.sign')) {
  const signed = await resolver.execute('crypto.sign', data);
}
```

### Unit Information
```typescript
console.log(resolver.whoami());
// "I am PureDIDResolverUnit v1.0.9 - Zero-dependency DID resolver"

console.log(resolver.help());
// Returns detailed capability documentation

console.log(resolver.dna);
// { id: 'pure-did-resolver', version: '1.0.9', created: '...' }
```

## API Reference

### Core Methods

#### `resolve(did: string, options?: ResolutionOptions): Promise<DIDResolutionResult>`
Resolves a DID to its DID document.

#### `parse(did: string): DIDParseResult | null`
Parses a DID string into components.

#### `clearCache(): void`
Clears the resolution cache.

#### `getStats(): ResolverStats`
Returns performance and cache statistics.

### Unit Architecture Methods

#### `teach(): TeachingContract`
Returns capabilities that can be taught to other units.

#### `learn(teachings: TeachingContract[]): void`
Learns capabilities from other units.

#### `can(capability: string): boolean`
Checks if a capability is available.

#### `execute(capability: string, ...args: unknown[]): Promise<unknown>`
Executes a learned capability.

## Types

```typescript
interface DIDResolutionResult {
  didDocument: DIDDocument | null;
  didResolutionMetadata: DIDResolutionMetadata;
  didDocumentMetadata: DIDDocumentMetadata;
}

interface DIDParseResult {
  did: string;
  components: DIDComponents;
  isValid: boolean;
  error?: string;
}

interface DIDComponents {
  method: 'key' | 'web';
  identifier: string;
  path?: string;
  query?: Record<string, string>;
  fragment?: string;
}
```

## Error Handling

```typescript
try {
  const result = await resolver.resolve('did:invalid:example');
} catch (error) {
  console.log(error.message); // Clear error descriptions
}

// Or check resolution metadata
const result = await resolver.resolve('did:unsupported:example');
if (result.didResolutionMetadata.error) {
  console.log('Resolution failed:', result.didResolutionMetadata.error);
}
```

## Dependencies

- `@synet/unit` - Unit Architecture foundation
- No external dependencies

## License

MIT

## Contributing

This package follows Unit Architecture patterns. See `packages/unit/DOCTRINE.md` for development guidelines.