# Marked

Marked is a high-performance, low-level markdown compiler that parses markdown without caching or blocking operations. It supports CommonMark and GitHub Flavored Markdown with zero runtime dependencies.

## Quick Start

```javascript { .api }
import { marked } from "marked";

const html = marked.parse('# Hello **World**');
// Output: <h1>Hello <strong>World</strong></h1>
```

**Security**: Marked does not sanitize HTML. Always use [DOMPurify](https://www.npmjs.com/package/dompurify) on output.

[→ Complete Quick Start Guide](./guides/quick-start.md)

## Package Information

- **Package**: `marked` (npm)
- **Language**: JavaScript/TypeScript
- **Installation**: `npm install marked`
- **Node.js**: >= 20
- **Bundle Size**: ~20KB minified
- **Dependencies**: Zero

## Core API

| Function | Purpose | Returns |
|----------|---------|---------|
| `marked.parse(src, options?)` | Parse markdown to HTML | `string \| Promise<string>` |
| `marked.parseInline(src, options?)` | Parse inline markdown only | `string \| Promise<string>` |
| `marked.setOptions(options)` | Set global options | `typeof marked` |
| `marked.use(...extensions)` | Add extensions | `typeof marked` |
| `marked.lexer(src, options?)` | Tokenize markdown | `TokensList` |
| `marked.parser(tokens, options?)` | Parse tokens to HTML | `string` |

[→ Complete API Reference](./reference/api.md)

## Core Imports

```javascript { .api }
// Main import
import { marked } from "marked";

// Specific imports
import {
  marked,           // Main parse function
  parse,            // Alias for marked
  parseInline,      // Parse inline markdown only
  Lexer,            // Tokenizer class
  Parser,           // Parser class
  Renderer,         // HTML renderer class
  Tokenizer,        // Low-level tokenizer class
  Hooks,            // Processing hooks class
  Marked            // Instance class for isolated configs
} from "marked";

// CommonJS
const { marked } = require("marked");
```

[→ Import Examples](./guides/quick-start.md#imports)

## Architecture

Marked uses a two-phase architecture:

1. **Lexing Phase**: `Lexer` tokenizes markdown into a structured token tree
2. **Parsing Phase**: `Parser` walks tokens and uses `Renderer` to generate HTML

**Processing Pipeline**:
```
Markdown → [Preprocess Hook] → Lexer → [ProcessAllTokens Hook] → 
[WalkTokens] → Parser + Renderer → [Postprocess Hook] → HTML
```

**Benefits**:
- Token manipulation between phases
- Custom renderers for different output formats
- Multi-pass processing
- Extension system at both phases

[→ Architecture Details](./reference/architecture.md)

## Key Features

### Markdown Support
- ✅ CommonMark specification
- ✅ GitHub Flavored Markdown (GFM)
  - Tables, strikethrough, task lists, autolinks
- ✅ Full Unicode support
- ✅ Pedantic mode (markdown.pl compatibility)

### Performance
- ⚡ Non-blocking parsing
- ⚡ No caching overhead
- ⚡ Optimized for large documents (<10ms for 100KB)
- ⚡ Zero dependencies

### Extensibility
- 🔧 Custom tokenizers for new syntax
- 🔧 Custom renderers for different output formats
- 🔧 Hooks for pipeline interception
- 🔧 Token walking for global modifications

[→ Extension System](./reference/extensions.md)

## Common Use Cases

| Use Case | Guide | Example |
|----------|-------|---------|
| Basic markdown parsing | [Quick Start](./guides/quick-start.md) | [Basic Usage](./examples/real-world-scenarios.md#basic-parsing) |
| Custom syntax | [Extensions Guide](./guides/extensions.md) | [Custom Tokens](./examples/real-world-scenarios.md#custom-syntax) |
| Syntax highlighting | [Rendering Guide](./guides/rendering.md) | [Code Highlighting](./examples/real-world-scenarios.md#syntax-highlighting) |
| Custom HTML output | [Rendering Guide](./guides/rendering.md) | [Custom Renderer](./examples/real-world-scenarios.md#custom-rendering) |
| Front matter support | [Extensions Guide](./guides/extensions.md) | [Front Matter](./examples/real-world-scenarios.md#front-matter) |
| Table of contents | [Token Walking](./guides/token-manipulation.md) | [TOC Generation](./examples/real-world-scenarios.md#table-of-contents) |

## Configuration

```javascript { .api }
// Set global options
marked.setOptions({
  gfm: true,        // Enable GitHub Flavored Markdown
  breaks: true,     // Convert \n to <br>
  pedantic: false,  // Don't fix markdown bugs
  silent: false     // Throw on errors
});

// Per-parse options
const html = marked.parse(markdown, { breaks: false });

// Isolated instances
const gfmMarked = new Marked({ gfm: true, breaks: true });
```

[→ Configuration Options](./reference/options.md)

## Extension System

Marked supports four types of extensions:

1. **Tokenizer Extensions**: Add new markdown syntax
2. **Renderer Extensions**: Customize HTML output
3. **Hooks**: Intercept processing pipeline
4. **walkTokens**: Process all tokens globally

```javascript { .api }
// Add custom emoji syntax
marked.use({
  extensions: [{
    name: 'emoji',
    level: 'inline',
    start(src) { return src.indexOf(':'); },
    tokenizer(src) {
      const match = src.match(/^:([a-z_]+):/);
      if (match) {
        return { type: 'emoji', raw: match[0], name: match[1] };
      }
    },
    renderer(token) {
      return `<span class="emoji emoji-${token.name}"></span>`;
    }
  }]
});
```

[→ Extension System Guide](./guides/extensions.md) | [→ Extension Reference](./reference/extensions.md)

## Security

**Critical**: Marked does NOT sanitize HTML output.

```javascript { .api }
import { marked } from "marked";
import DOMPurify from "dompurify";

// UNSAFE
const unsafeHtml = marked.parse(userInput);

// SAFE
const dirty = marked.parse(userInput);
const clean = DOMPurify.sanitize(dirty);
```

**Recommended sanitization libraries**:
- [DOMPurify](https://www.npmjs.com/package/dompurify) - Most comprehensive
- [sanitize-html](https://www.npmjs.com/package/sanitize-html) - Configurable
- [js-xss](https://www.npmjs.com/package/xss) - Lightweight

[→ Security Best Practices](./guides/security.md)

## Error Handling

```javascript { .api }
// Throw errors (default)
try {
  const html = marked.parse(markdown);
} catch (err) {
  console.error('Parse error:', err.message);
}

// Silent mode (return error as HTML)
marked.setOptions({ silent: true });
const html = marked.parse(markdown);
```

[→ Error Handling Guide](./guides/error-handling.md)

## Async Support

```javascript { .api }
// Enable async mode
marked.setOptions({ async: true });

// Use async extensions
marked.use({
  async: true,
  async walkTokens(token) {
    if (token.type === 'link') {
      await validateUrl(token.href);
    }
  }
});

// Must await result
const html = await marked.parse(markdown, { async: true });
```

[→ Async Patterns](./guides/async-patterns.md)

## CLI Usage

```bash
# Install globally
npm install -g marked

# Parse file
marked input.md -o output.html

# Parse with options
marked input.md --gfm --breaks

# From stdin
echo "# Hello" | marked
```

[→ CLI Reference](./reference/cli.md)

## Documentation Structure

### Guides (Step-by-Step)
- [Quick Start](./guides/quick-start.md) - Get started in minutes
- [Extensions](./guides/extensions.md) - Add custom syntax and rendering
- [Token Manipulation](./guides/token-manipulation.md) - Work with token trees
- [Rendering](./guides/rendering.md) - Customize HTML output
- [Security](./guides/security.md) - Secure markdown parsing
- [Error Handling](./guides/error-handling.md) - Handle parsing errors
- [Async Patterns](./guides/async-patterns.md) - Async parsing and extensions
- [Troubleshooting](./guides/troubleshooting.md) - Common issues and solutions

### Examples (Real-World Usage)
- [Real-World Scenarios](./examples/real-world-scenarios.md) - Complete examples
- [Edge Cases](./examples/edge-cases.md) - Advanced scenarios

### Reference (Detailed Specifications)
- [API Reference](./reference/api.md) - Complete API documentation
- [Architecture](./reference/architecture.md) - Internal architecture
- [Extensions](./reference/extensions.md) - Extension system details
- [Hooks](./reference/hooks.md) - Hook system reference
- [Lexer](./reference/lexer.md) - Lexer class reference
- [Parser & Renderer](./reference/parser-renderer.md) - Parser and Renderer classes
- [Tokenizer](./reference/tokenizer.md) - Tokenizer class reference
- [Types](./reference/types.md) - TypeScript types and token structures
- [Options](./reference/options.md) - Configuration options
- [CLI](./reference/cli.md) - Command-line interface

## Migration

### From Other Libraries

**From markdown-it**:
```javascript
// markdown-it
const md = require('markdown-it')();
const html = md.render(markdown);

// marked
import { marked } from "marked";
const html = marked.parse(markdown);
```

**From showdown**:
```javascript
// showdown
const converter = new showdown.Converter();
const html = converter.makeHtml(markdown);

// marked
import { marked } from "marked";
const html = marked.parse(markdown);
```

[→ Migration Guide](./guides/migration.md)

## Performance

- **Non-blocking**: No I/O operations
- **No caching**: Each parse is independent
- **Memory efficient**: Tokens kept in memory during parsing only
- **Fast**: <10ms for 100KB documents (typical)

```javascript { .api }
// Cache results for repeated content
const cache = new Map();

function cachedParse(markdown) {
  if (cache.has(markdown)) {
    return cache.get(markdown);
  }
  const html = marked.parse(markdown);
  cache.set(markdown, html);
  return html;
}
```

[→ Performance Guide](./guides/performance.md)

## TypeScript Support

Full TypeScript support with comprehensive type definitions:

```typescript { .api }
import { marked, MarkedOptions, Token, Tokens } from "marked";

// Type-safe configuration
const options: MarkedOptions = {
  gfm: true,
  breaks: true
};

// Type guards for token handling
function processToken(token: Token): void {
  if (token.type === 'heading') {
    // TypeScript knows this is Tokens.Heading
    console.log(`Level ${token.depth}: ${token.text}`);
  }
}
```

[→ TypeScript Guide](./guides/typescript.md)

## Resources

- **GitHub**: [markedjs/marked](https://github.com/markedjs/marked)
- **npm**: [marked](https://www.npmjs.com/package/marked)
- **Issues**: [GitHub Issues](https://github.com/markedjs/marked/issues)
- **CommonMark Spec**: [commonmark.org](https://commonmark.org/)
- **GFM Spec**: [github.github.com/gfm](https://github.github.com/gfm/)

## Notes

- **No HTML Sanitization**: Use DOMPurify or similar on output
- **GFM Enabled by Default**: Tables, strikethrough, task lists, autolinks
- **Zero Dependencies**: No runtime dependencies
- **Browser Support**: All modern browsers (Baseline Widely Available)
- **Node.js**: Requires Node.js >= 20
- **Unicode**: Full Unicode support in pattern matching
- **Compliance**: Supports CommonMark and GFM specifications
