# TCSS WebAssembly Implementation
This document describes the WebAssembly bindings implementation for TCSS.
## Overview
The TCSS WASM module provides a browser-compatible interface to the TCSS compiler, allowing TCSS to be compiled to CSS directly in web browsers and Node.js environments without requiring a server-side build step.
## Architecture
### Module Structure
```
tcss-wasm/
├── Cargo.toml # Package configuration with WASM optimizations
├── src/
│ └── lib.rs # WASM bindings and exported functions
├── tests/
│ └── web.rs # WASM integration tests
├── build.sh # Build script for different targets
├── example.html # Interactive demo
├── package.json # npm package configuration
└── README.md # User documentation
```
### Key Components
1. **WASM Bindings (`src/lib.rs`)**
- Exports compilation functions to JavaScript
- Handles error conversion from Rust to JavaScript
- Provides utility functions for parsing and validation
2. **Build Configuration (`Cargo.toml`)**
- Optimized for size with `opt-level = "z"`
- Link-time optimization (LTO) enabled
- Symbol stripping for smaller bundles
- cdylib crate type for WASM output
3. **Integration Tests (`tests/web.rs`)**
- Browser-based tests using wasm-bindgen-test
- Tests all exported functions
- Validates error handling
## Exported Functions
### `compile_tcss(input: &str) -> Result<String, JsValue>`
Main compilation function that converts TCSS to CSS.
**Process:**
1. Tokenize input using `Lexer`
2. Parse tokens into AST using `Parser`
3. Generate CSS using `Generator`
4. Return formatted CSS or error
**Example:**
```javascript
const css = compile_tcss('.button:\n padding: 16px');
```
### `compile_tcss_minified(input: &str) -> Result<String, JsValue>`
Compiles TCSS to minified CSS for production use.
**Example:**
```javascript
const css = compile_tcss_minified('.button:\n padding: 16px');
// Returns: ".button{padding:16px;}"
```
### `compile_tcss_with_options(input: &str, minify: bool) -> Result<String, JsValue>`
Flexible compilation with custom options.
**Example:**
```javascript
const css = compile_tcss_with_options(tcss, true);
```
### `parse_tcss(input: &str) -> Result<JsValue, JsValue>`
Parses TCSS and returns the AST as a JavaScript object.
**Use cases:**
- Debugging
- Tooling (linters, formatters)
- IDE integration
**Example:**
```javascript
const ast = parse_tcss('.button:\n padding: 16px');
console.log(ast);
```
### `validate_tcss(input: &str) -> Result<bool, JsValue>`
Validates TCSS syntax without generating CSS.
**Example:**
```javascript
try {
validate_tcss(tcss);
console.log('Valid TCSS!');
} catch (error) {
console.error('Invalid:', error);
}
```
## Memory Management
The WASM module uses `wasm-bindgen` for automatic memory management:
- **Strings**: Automatically converted between Rust `String` and JavaScript `string`
- **Errors**: Rust `Result` types are converted to JavaScript exceptions
- **Objects**: Serialized using `serde-wasm-bindgen` for AST export
No manual memory management is required from JavaScript.
## Error Handling
Errors are converted from Rust to JavaScript using `JsValue`:
```rust
.map_err(|e| JsValue::from_str(&format!("Lexer error: {}", e)))?
```
This allows JavaScript code to use standard try-catch:
```javascript
try {
const css = compile_tcss(tcss);
} catch (error) {
console.error('Compilation failed:', error);
}
```
## Build Optimization
### Size Optimization
The `Cargo.toml` includes aggressive size optimizations:
```toml
[profile.release]
opt-level = "z" # Optimize for size
lto = true # Link-time optimization
codegen-units = 1 # Better optimization
strip = true # Remove debug symbols
```
### Build Targets
The module supports multiple build targets:
- **web**: For direct browser use with ES modules
- **nodejs**: For Node.js environments
- **bundler**: For webpack, rollup, etc.
## Testing
### Unit Tests
Standard Rust tests in `src/lib.rs` test the Rust API.
### Integration Tests
WASM-specific tests in `tests/web.rs` run in actual browsers:
```bash
wasm-pack test --headless --firefox
wasm-pack test --headless --chrome
```
### Manual Testing
The `example.html` file provides an interactive demo:
```bash
# Build the module
wasm-pack build --target web
# Serve the example
python3 -m http.server 8080
# Open http://localhost:8080/example.html
```
## Performance Considerations
1. **Initialization**: The WASM module must be initialized before use:
```javascript
await init();
```
2. **Compilation Speed**: WASM compilation is fast (typically <10ms for small files)
3. **Bundle Size**: Optimized builds are typically 100-200KB (gzipped)
4. **Memory Usage**: Minimal overhead, strings are copied between Rust and JS
## Browser Compatibility
The WASM module works in all modern browsers that support:
- WebAssembly
- ES6 modules
- Async/await
Supported browsers:
- Chrome 61+
- Firefox 60+
- Safari 11+
- Edge 79+
## Publishing
### To npm
```bash
wasm-pack build --target bundler
wasm-pack publish
```
### To crates.io
```bash
cargo publish -p tcss-wasm
```
## Future Enhancements
1. **Streaming API**: Support for large files
2. **Source Maps**: Generate source maps for debugging
3. **Worker Support**: Run compilation in Web Workers
4. **Incremental Compilation**: Cache and reuse parsed AST
5. **Custom Error Types**: Structured error objects instead of strings
## References
- [wasm-bindgen documentation](https://rustwasm.github.io/wasm-bindgen/)
- [wasm-pack documentation](https://rustwasm.github.io/wasm-pack/)
- [WebAssembly specification](https://webassembly.org/)