# Bamboo CSS System Architecture

## Overview

Bamboo CSS is a universal, build-time, type-safe, zero-runtime CSS-in-JS solution that extracts styles at compile time
and generates optimized CSS and TypeScript utilities. The system follows a modular architecture built as a pnpm monorepo
with distinct packages handling different aspects of the styling pipeline.

## Core Philosophy

- **Build-time extraction**: Styles are analyzed and extracted during the build process, not at runtime
- **Type safety**: Full TypeScript support with auto-generated types based on configuration
- **Zero runtime**: CSS is generated at build time, minimal JavaScript shipped to the browser
- **Framework agnostic**: Works with React, Vue, Svelte, Solid, Preact, Qwik, and more
- **Modern CSS**: Leverages CSS custom properties, cascade layers (`@layer`), and modern CSS features

## Repository Structure

```
bamboo/
├── packages/           # Core packages (published to npm)
├── sandbox/           # Framework integration examples
├── playground/        # Development testing environment
├── website/           # Documentation site
└── .changeset/        # Changeset-based versioning
```

## Package Architecture

### 1. User-Facing Packages

#### `@bamboocss/dev` (packages/cli)

- **Purpose**: Main entry point for end users
- **Exports**: CLI binary (`bamboo` command), PostCSS plugin, presets
- **Key responsibilities**:
  - Command-line interface (init, codegen, build, analyze, debug)
  - Interactive setup wizard
  - Update notifications
- **Dependencies**: Orchestrates all other packages

#### `@bamboocss/postcss` (packages/postcss)

- **Purpose**: PostCSS plugin integration
- **Key responsibilities**:
  - Integrates Bamboo into PostCSS build pipeline
  - Uses `Builder` class to process CSS files
  - Registers file dependencies for hot module replacement
  - Validates and processes Bamboo-specific CSS

### 2. Core Processing Packages

#### `@bamboocss/core` (packages/core)

- **Purpose**: Heart of the Bamboo system containing all core logic
- **Key classes**:
  - **Context**: Central orchestration class that manages all engines
  - **Utility**: CSS utility generation and processing
  - **Recipes**: Component recipe/variant system (like Stitches)
  - **Patterns**: Layout pattern generation (flex, grid, container, etc.)
  - **Conditions**: Responsive/conditional style handling (breakpoints, pseudo-classes)
  - **Stylesheet**: CSS generation and optimization
  - **StyleEncoder/StyleDecoder**: Style serialization and deserialization
  - **TokenDictionary**: Design token management
  - **JsxEngine**: JSX component analysis
  - **ImportMap**: Import tracking for bamboo functions
- **Key responsibilities**:
  - Style transformation and serialization
  - CSS optimization and minification
  - Layer management (`@layer` directives)
  - Selector parsing and manipulation
  - Color mixing utilities

#### `@bamboocss/parser` (packages/parser)

- **Purpose**: Static code analysis and extraction
- **Key responsibilities**:
  - TypeScript/JavaScript AST parsing (uses ts-morph)
  - Vue SFC parsing (uses @vue/compiler-sfc)
  - Svelte component parsing
  - Extracting style declarations from source code
  - Matching function calls and JSX props against Bamboo APIs
- **Key classes**:
  - **Project**: Manages ts-morph project for file analysis
  - **ParserResult**: Collects and organizes extraction results

#### `@bamboocss/extractor` (packages/extractor)

- **Purpose**: Low-level AST extraction and evaluation
- **Key responsibilities**:
  - Extracting values from AST nodes
  - Static evaluation of expressions (uses ts-evaluator)
  - Box/unbox pattern for value wrapping
  - JSX attribute and spread analysis
  - Object literal analysis
- **Core concepts**:
  - **Boxing**: Wrapping AST nodes with metadata
  - **Evaluation**: Computing static values from code

#### `@bamboocss/generator` (packages/generator)

- **Purpose**: Code generation for styled-system output
- **Directory structure**:
  ```
  artifacts/
  ├── css/           # CSS generation (tokens, reset, static, global, keyframes)
  ├── js/            # JavaScript utility functions
  ├── types/         # TypeScript type definitions
  └── generated/     # Generated helper files
  ```
- **Key responsibilities**:
  - Generating the `styled-system` directory
  - Type definition generation for autocomplete
  - CSS utility classes
  - Pattern and recipe types/functions

There is no `jsx/` artifact directory. The JSX factory was removed, so `styled-system/jsx` is not generated and there
are no framework-specific factories to emit — a class name comes from a call the compiler can see, or from `staticCss`,
which pre-generates rules with no call site.

### 3. Configuration & Setup

#### `@bamboocss/config` (packages/config)

- **Purpose**: Configuration loading and merging
- **Key responsibilities**:
  - Finding and loading `bamboo.config.ts/js`
  - Dynamic config import with bundle-n-require
  - Merging user config with presets
  - Config diffing for incremental updates
  - TypeScript path mapping resolution

#### `@bamboocss/preset-*` (packages/preset-\*)

- **Available presets**:
  - `preset-base`: Minimal foundation preset
  - `preset-bamboo`: Default preset with design system tokens
  - `preset-atlaskit`: Atlassian design system integration
  - `preset-open-props`: Open Props design tokens
- **Purpose**: Shareable configuration and design tokens

### 4. Orchestration & Build

#### `@bamboocss/node` (packages/node)

- **Purpose**: Node.js runtime and build orchestration
- **Key classes/functions**:
  - **BambooContext**: Extended context with build-time features
  - **Builder**: Incremental build system with file watching
  - **DiffEngine**: Detects configuration changes
  - **OutputEngine**: Manages file writing
- **Key responsibilities**:
  - File watching (chokidar)
  - Incremental builds
  - Config change detection
  - Git ignore management
  - CSS generation and optimization
  - oxfmt formatting integration

### 5. Utilities & Infrastructure

#### `@bamboocss/token-dictionary` (packages/token-dictionary)

- **Purpose**: Design token processing
- **Key responsibilities**:
  - Token transformation and references
  - Semantic token resolution
  - CSS variable generation
  - Token categorization (colors, spacing, typography, etc.)
- **Critical API distinction**:
  - `get(path)`: Returns raw token values (e.g., `"#ef4444"`, `"1rem"`)
  - `getVar(path)`: Returns CSS variable references (e.g., `"var(--colors-red-500)"`)
  - Use `getVar()` for RuleProcessor and string pattern expansion
  - Use `get()` for AST evaluation of token CallExpressions

#### `@bamboocss/types` (packages/types)

- **Purpose**: Shared TypeScript types
- **Build process**: Generates complex conditional types from csstype
- **Exports**: All type definitions used across packages

#### `@bamboocss/shared` (packages/shared)

- **Purpose**: Shared utility functions
- **Examples**: Object manipulation, string utilities, memoization, pattern functions

#### `@bamboocss/is-valid-prop` (packages/is-valid-prop)

- **Purpose**: Validates CSS property names
- **Used by**: Core and generator for prop filtering

#### `@bamboocss/logger` (packages/logger)

- **Purpose**: Centralized logging with log levels
- **Features**: Colored output, timing utilities, debug mode

#### `@bamboocss/reporter` (packages/reporter)

- **Purpose**: User-friendly error and warning messages

#### `@bamboocss/vite` (packages/vite)

- **Purpose**: Vite plugin — emits the stylesheet and compiles `css()`, pattern and recipe calls into globally shared
  atomic classes at build time
- **Key responsibilities**: strict whole-program compilation, finite recipe decision tables, graph pruning and the
  virtual `virtual:bamboo.css` module

#### `@bamboocss/mcp` (packages/mcp)

- **Purpose**: MCP server exposing tokens, recipes, patterns and usage reports to AI assistants

#### `@bamboocss/eslint-plugin` (packages/eslint-plugin)

- **Purpose**: Lint rules (e.g. `no-dynamic-styling`, `no-config-function-in-source`, `require-literal-token-path`)

#### `@bamboocss/plugin-*` (packages/plugin-lightningcss, plugin-vue, plugin-svelte)

- **Purpose**: Optional plugins. `vue` and `svelte` are auto-injected for their file types; `lightningcss` is installed
  and listed by the user.

#### `@bamboocss/fixture` (packages/fixture)

- **Purpose**: Shared test fixtures and context factories (`createContext`, `createRuleProcessor`). Private — not
  published to npm.

## System Flow

### 1. Initialization Flow (`bamboo init`)

```
User runs `bamboo init`
    ↓
CLI (packages/cli)
    ↓
Interactive wizard or flag parsing
    ↓
setupConfig() - Creates bamboo.config.ts
    ↓
setupPostcss() - Optional postcss.config.js
    ↓
loadConfigAndCreateContext() - Loads and validates config
    ↓
codegen() - Generates styled-system directory
    ↓
setupGitIgnore() - Updates .gitignore
```

### 2. Build/Watch Flow (`bamboo` or `bamboo --watch`)

```
User runs `bamboo`
    ↓
CLI (packages/cli)
    ↓
Builder.setup()
    ├─→ Find config (packages/config)
    ├─→ Load config with presets
    ├─→ Create Context (packages/core)
    │   ├─→ Initialize TokenDictionary
    │   ├─→ Initialize Utility engine
    │   ├─→ Initialize Recipes
    │   ├─→ Initialize Patterns
    │   └─→ Initialize Conditions
    ↓
Builder.emit() - Generate baseline CSS & JS
    ↓
Builder.extract() - Scan source files
    ├─→ Fast-glob finds files
    ├─→ Parser (packages/parser)
    │   ├─→ ts-morph creates AST
    │   ├─→ Extractor (packages/extractor)
    │   │   └─→ Extract style objects
    │   └─→ Returns ParserResult
    ↓
Generator (packages/generator)
    ├─→ Generate artifacts
    │   ├─→ CSS files (tokens, utilities, reset)
    │   ├─→ JS files (css, cva, sva, patterns)
    │   └─→ TypeScript types
    ↓
Builder.write() - Write files to styled-system
    ↓
Optimize CSS (postcss plugins)
    └─→ Format with oxfmt
```

### 3. PostCSS Integration Flow

```
Build tool runs PostCSS
    ↓
@bamboocss/postcss plugin
    ↓
Builder.setup() - Same as above
    ↓
Builder.isValidRoot() - Check for Bamboo CSS
    ↓
Builder.emit() - Generate artifacts
    ↓
Builder.extract() - Extract from changed files
    ↓
Builder.write(root) - Inject CSS into PostCSS AST
    ↓
Register dependencies for HMR
```

### 4. Parser Extraction Flow

```
Source file (e.g., App.tsx)
    ↓
ts-morph creates SourceFile
    ↓
getImportDeclarations() - Find bamboo imports
    ├─→ css(), cva(), sva(), token(), viewTransition(), etc.
    ↓
extract() from @bamboocss/extractor
    ├─→ Scan for function calls
    │   └─→ Match against ImportMap
    ↓
For each match:
    ├─→ box() - Wrap AST node
    ├─→ Evaluate statically (with token resolution if needed)
    └─→ unbox() - Extract value
    ↓
Parser match statement (packages/parser/src/parser.ts:311-391)
    ├─→ .when(imports.matchers.css.match) - Handle css/cva/sva
    ├─→ .when(imports.matchers.tokens.match) - Handle token() calls
    ├─→ .when(file.isValidPattern) - Handle pattern functions
    ├─→ .when(file.isValidRecipe) - Handle recipe functions
    └─→ .when(file.isViewTransitionFn) - Handle viewTransition() calls
    ↓
JSX recipe components (parser.ts:393, when `jsx.isEnabled`)
    └─→ jsx.isJsxTagRecipe(tag) - a recipe component the project wrote itself, whose
        variant props are only visible at the call site. Driven by a recipe's `jsx` key,
        not by a styled factory.
    ↓
ParserResult
    ├─→ set('css' | 'cva' | 'sva', ...) - dispatches to setCss/setCva/setSva
    ├─→ setToken(...) - Store token references
    ├─→ setPattern(...) - Store pattern usage
    ├─→ setRecipe(...) - Store recipe usage
    ├─→ setViewTransition(...) - Store view transition names
    ↓
StyleEncoder - Encode to atomic classes
    ├─→ Store in StyleDecoder
    └─→ Return extracted styles
```

**Token Extraction Details**: When `token()` is encountered:

1. `imports.matchers.tokens.match` identifies token imports (packages/core/src/import-map.ts:25)
2. Parser extracts the token CallExpression arguments (packages/parser/src/parser.ts:165-176)
3. Extractor evaluates the token path and optional fallback (packages/extractor/src/maybe-box-node.ts)
4. TokenDictionary resolves the path:
   - `get(path)` returns raw value for base tokens
   - `getVar(path)` returns CSS variable for semantic/virtual tokens
5. Result is stored in ParserResult with `setToken()`

### 5. Code Generation Flow

```
Generator.getArtifacts()
    ↓
generateArtifacts() dispatches to:
    ├─→ CSS Artifacts
    │   ├─→ generateResetCss() - Preflight/reset
    │   ├─→ generateTokenCss() - CSS variables
    │   ├─→ generateStaticCss() - Static utilities
    │   ├─→ generateGlobalCss() - Global styles
    │   └─→ generateKeyframeCss() - @keyframes
    ├─→ JS Artifacts
    │   ├─→ css.mjs - Main styling API
    │   ├─→ cva.mjs - Component variants
    │   ├─→ sva.mjs - Slot variants
    │   ├─→ patterns/*.mjs - Layout patterns
    │   └─→ recipes/*.mjs - Recipe functions
    └─→ Type Artifacts
        ├─→ style-props.d.ts
        ├─→ pattern.d.ts
        └─→ recipes/types.d.ts
```

## Key Design Patterns

### 1. Context Pattern

- **Context** class is the central orchestrator
- All engines (Utility, Recipes, Patterns, etc.) are initialized in Context
- Context is passed down to all subsystems
- Provides unified access to configuration, tokens, and utilities

### 2. Engine Pattern

- Specialized engines handle different concerns:
  - **Utility**: CSS utility generation
  - **Recipes**: Component recipes
  - **Patterns**: Layout patterns
  - **JsxEngine**: JSX analysis
  - **PathEngine**: File path management
  - **FileEngine**: File template management

### 3. Builder Pattern

- **Builder** class manages incremental builds
- Tracks file changes and config diffs
- Coordinates setup → extract → generate → write cycle
- Handles file watching and HMR

### 4. Encoder/Decoder Pattern

- **StyleEncoder**: Converts style objects to atomic class names
- **StyleDecoder**: Collects all encoded styles for CSS generation
- Enables atomic CSS with automatic deduplication

### 5. Box/Unbox Pattern (Extractor)

- **Boxing**: Wraps AST nodes with metadata and utilities
- **Evaluation**: Computes static values
- **Unboxing**: Extracts final values
- Handles complex expressions, spreads, and conditionals

### 6. Token Resolution Strategy

Bamboo CSS has a dual-mode token resolution system that handles tokens differently based on context:

#### CallExpression Mode (AST Extraction)

When `token()` appears as a **CallExpression** in the AST (i.e., actually called as a function):

```typescript
// Template literal interpolation with CallExpression
const styles = css({
  border: `1px solid ${token('colors.yellow.100')}`, // token() is called
})
```

**Resolution**: The extractor evaluates `token()` calls **at build time** and resolves them to:

- **Base tokens** (no conditions) → Raw value (e.g., `"#fef9c3"`)
- **Semantic/conditional tokens** → CSS variable (e.g., `"var(--colors-primary)"`)
- **Virtual tokens** (colorPalette) → CSS variable (e.g., `"var(--colors-color-palette-500)"`)

**Key files**:

- `packages/extractor/src/maybe-box-node.ts` - Handles token CallExpression evaluation
- `packages/token-dictionary/src/dictionary.ts` - `get()` returns raw values, `getVar()` returns CSS variables

#### String Pattern Mode (RuleProcessor)

When `token(...)` appears as a **string pattern** (not executed as a function):

```typescript
// String literal with token pattern
const styles = css({
  border: '1px solid token(colors.yellow.100)', // Plain string, no CallExpression
})
```

**Resolution**: The RuleProcessor pattern-matches the string **after parsing** via `expandReferenceInValue()`:

- Finds pattern: `token(path.to.token)`
- Always resolves to CSS variable: `"var(--path-to-token)"`

**Key files**:

- `packages/token-dictionary/src/dictionary.ts:392-411` - `expandReferenceInValue()` method
- `packages/core/src/utility.ts:262` - `getToken()` uses `getVar()` for CSS variable output
- `packages/core/src/utility.ts:400` - `defaultTransform()` uses `getVar()` for CSS custom properties

#### Critical Distinction

| Context                               | Example                                         | Resolution                    | Output                                 |
| ------------------------------------- | ----------------------------------------------- | ----------------------------- | -------------------------------------- |
| **Template literal + CallExpression** | `` `1px solid ${token('colors.yellow.100')}` `` | AST evaluation → Raw value    | `"1px solid #fef9c3"`                  |
| **String pattern (no call)**          | `"1px solid token(colors.yellow.100)"`          | RuleProcessor → CSS variable  | `"1px solid var(--colors-yellow-100)"` |
| **Object property + CallExpression**  | `{ color: token('colors.red.500') }`            | AST evaluation → Raw value    | `{ color: "#ef4444" }`                 |
| **Object property + token()**         | `{ color: token.value('colors.red.500') }`      | AST evaluation → CSS variable | `{ color: "var(--colors-red-500)" }`   |

#### Why This Design?

This dual-mode system exists because:

1. **Template literals with interpolation** execute functions at runtime, so build-time evaluation must match runtime
   behavior
2. **String patterns** are processed by Bamboo's RuleProcessor and can be transformed to CSS variables for dynamic
   theming
3. **Semantic tokens** (with conditions) must always use CSS variables to support responsive/conditional values
4. Users can explicitly request CSS variables with `token()` when needed in CallExpressions

## Build Optimization

### Incremental Builds

- **File tracking**: Tracks modified times of source and config files
- **Dependency graph**: Knows which files affect what artifacts
- **Smart invalidation**: Only regenerates changed artifacts
- **Config diffing**: Detects specific config changes to minimize regeneration

### CSS Optimization

- **Atomic CSS**: Each unique style gets one class
- **Layer ordering**: Uses `@layer` for predictable cascade
- **PostCSS pipeline** (the default; `packages/core/src/optimize.ts` dispatches, the plugin order lives in
  `packages/core/src/plugins/optimize-postcss.ts`):
  - `nested()` - Unwrap nested rules
  - `dedupeNodes()` - Remove duplicate rules (local, not `postcss-discard-duplicates`)
  - `mergeRules()` - Merge duplicate selectors (inlined as `packages/core/src/plugins/merge-rules.ts`, so core does not
    depend on browserslist or caniuse-api)
  - `discardEmpty()` - Drop empty rules
  - then `normalizeWhiteSpace()` + `minifySelectors()` under `minify`, else `prettify()`
- **LightningCSS** - an opt-in _alternative_ to that pipeline, not a stage in it. Install
  `@bamboocss/plugin-lightningcss` and list `pluginLightningcss()` in `plugins`; it answers the `css:optimize` hook.

### Code Splitting

- Separate artifacts for different concerns
- Lazy-loadable pattern and recipe functions
- Tree-shakeable exports

## Type System

### Generated Types

```typescript
// Utility props
css({ color: 'red.500' }) // Autocomplete for 'red.500'

// Pattern props
flex({ gap: '4' }) // Autocomplete for spacing tokens

// Recipe variants
button({ size: 'lg', variant: 'solid' }) // Autocomplete variants
```

### Type Generation Flow

```
User config (theme.tokens)
    ↓
TokenDictionary processes tokens
    ↓
Generator creates type definitions
    ├─→ Token paths as string literals
    ├─→ Recipe variant types
    ├─→ Pattern prop types
    └─→ Utility prop types
    ↓
TypeScript provides autocomplete
```

## Framework Integration

### One Authoring API Across Frameworks

There is no JSX factory and no style props. Every framework authors styles the same way — a `css()`, pattern or recipe
call whose result is a class string — so nothing framework-specific is generated:

```tsx
import { css } from './styled-system/css'
;<div className={css({ color: 'red.500' })} />
```

That is what makes whole-program compilation possible: the call is visible to `@bamboocss/vite`, which resolves its
declarations into the global atom pool and replaces it with the resulting compact class value. See `packages/vite` and
the source-compilation guide.

### Framework-Specific Parsing

- **React/Preact**: Standard JSX
- **Vue**: SFC parsing with `@vue/compiler-sfc`
- **Svelte**: Component parsing with custom transformer
- **Solid**: JSX with Solid-specific patterns

## Plugin System

### Hooks API

Bamboo provides a hookable API for extensibility. Hooks register through `plugins` only — there is no top-level `hooks`
config option, and setting one is a hard error:

```typescript
plugins: [
  {
    name: 'my-app',
    hooks: {
      'tokens:created': (args) => {
        /* Modify tokens */
      },
      'parser:before': (args) => {
        /* Pre-parsing */
      },
      'parser:after': (args) => {
        /* Post-parsing */
      },
      'cssgen:done': (args) => {
        /* Post-CSS generation */
      },
      'codegen:prepare': (args) => {
        /* Pre-codegen */
      },
    },
  },
]
```

### Plugin Architecture

Plugins can:

- Modify token dictionary
- Add custom utilities
- Transform generated code
- Integrate with build tools

## Testing Strategy

### Test Infrastructure

- **Vitest**: Test runner with globals
- **Happy-dom**: Browser environment simulation
- **Unit tests**: Per-package in `__tests__` directories
- **Integration tests**: In sandbox directories
- **Fixtures**: Sample projects in `packages/fixture`

### Test Coverage Areas

1. **Config loading**: Various config formats and merging
2. **Token processing**: Token transformation and references
3. **Parser**: AST extraction accuracy
4. **Generator**: Artifact generation correctness
5. **CSS output**: Style transformation and optimization
6. **Type generation**: TypeScript type correctness

## Development Workflow

### Local Development

```bash
pnpm install              # Install dependencies
pnpm build-fast          # Quick build without types
pnpm dev                 # Watch mode for packages
pnpm playground          # Run playground examples
```

### Package Scripts

- `build`: Full build with types
- `build-fast`: Quick build, no type generation
- `dev`: Watch mode
- `test`: Run tests
- `typecheck`: TypeScript validation

### Release Process

1. Changes tracked with Changesets (`.changeset/`)
2. Run `pnpm changeset` to document changes
3. Changesets generates changelog and version bumps
4. `pnpm release` publishes to npm

## Performance Considerations

### Build Performance

- **Lazy imports**: Delays loading until needed
- **Parallel processing**: Uses `pnpm --parallel` for multi-package builds
- **Caching**: ts-morph caches parsed ASTs
- **Fast glob**: Efficient file scanning

### Runtime Performance

- **Zero runtime**: All styles generated at build time
- **Minimal JS**: Only necessary utility functions shipped
- **CSS variables**: Dynamic theming without JS
- **Tree-shaking**: Unused utilities eliminated

### Memory Management

- **Memoization**: Expensive computations cached
- **Streaming**: Large file processing in chunks
- **Context cleanup**: Proper disposal of resources

## Error Handling

### User-Facing Errors

- **Reporter package**: Formatted, helpful error messages
- **Logger levels**: debug, info, warn, error, silent
- **Stack traces**: Preserved for debugging
- **Suggestions**: Actionable error messages

### Error Categories

1. **Config errors**: Invalid configuration
2. **Parse errors**: Malformed source code
3. **Generation errors**: Failed artifact creation
4. **File system errors**: Permission/access issues

## Common Pitfalls & Debugging

### Token Resolution Issues

**Pitfall**: Using `tokens.view.get()` when CSS variables are needed

```typescript
// ❌ WRONG - Returns raw value when CSS variable needed
const tokenValue = this.tokens.view.get(path) // Returns "#ef4444"

// ✅ CORRECT - Returns CSS variable for RuleProcessor
const tokenValue = this.tokens.view.getVar(path) // Returns "var(--colors-red-500)"
```

**When to use each**:

- Use `get()`: When evaluating token CallExpressions in AST (extractor phase)
- Use `getVar()`: When processing string patterns in RuleProcessor (expandReferenceInValue, getToken, defaultTransform)

**Common locations that need `getVar()`**:

- `packages/core/src/utility.ts:262` - `getToken()` method
- `packages/core/src/utility.ts:400` - `defaultTransform()` method
- `packages/token-dictionary/src/dictionary.ts:392-411` - `expandReferenceInValue()` method

### Parser Matcher Type Safety

**Pitfall**: Including function names in matcher type that aren't actually matched

```typescript
// ❌ WRONG - 'token' is not matched by imports.matchers.css
.when(imports.matchers.css.match, (name: 'css' | 'cva' | 'sva' | 'token') => {
  // This will never receive 'token' as name!
})

// ✅ CORRECT - Separate matchers for different function types
.when(imports.matchers.css.match, (name: 'css' | 'cva' | 'sva') => {
  // Handle css/cva/sva
})
.when(imports.matchers.tokens.match, (name: 'token') => {
  // Handle token
})
```

**Check matcher configuration**: Look at `packages/core/src/import-map.ts` to see what each matcher actually matches.

### Template Literal vs String Pattern

**Pitfall**: Confusing template literal interpolation with string patterns

```typescript
// Template literal with CallExpression - Resolved at AST extraction
border: `1px solid ${token('colors.yellow.100')}`
// → Result: "1px solid #fef9c3" (raw value)

// String pattern - Resolved by RuleProcessor
border: '1px solid token(colors.yellow.100)'
// → Result: "1px solid var(--colors-yellow-100)" (CSS variable)
```

**Debugging tip**: Check if `token()` appears inside `${}` interpolation or as plain text in the string.

### Missing Parser Handlers

**Pitfall**: Adding new function types to ImportMap but forgetting to add parser handlers

**Checklist when adding new function types**:

1. ✅ Add to `packages/core/src/import-map.ts` matcher configuration
2. ✅ Add `.when()` case in `packages/parser/src/parser.ts` switch statement
3. ✅ Add storage method in `packages/parser/src/parser-result.ts` (e.g., `setToken()`)
4. ✅ Add result type to `packages/types/src/parser.ts` if needed
5. ✅ Write tests in `packages/parser/__tests__/`

### Debugging Token Resolution

**Enable debug logging**:

```bash
DEBUG=* bamboo
```

Look for these log messages:

- `ast:import` - Shows what imports were found
- `ast:css`, `ast:token`, etc. - Shows what functions were extracted
- Token resolution paths in extractor

**Test both modes**:

- Write tests for CallExpression evaluation (token.test.ts)
- Write tests for string pattern resolution (output.test.ts)
- Ensure semantic and virtual tokens resolve to CSS variables

## Future Architecture Considerations

### Extensibility Points

- Custom pattern definitions
- Plugin marketplace
- Framework adapters
- Build tool integrations

### Scalability

- Multi-threaded parsing for large codebases
- Distributed caching for monorepos
- Incremental type checking
- Remote artifact caching

## Conclusion

Bamboo CSS architecture emphasizes:

- **Modularity**: Clear separation of concerns across packages
- **Performance**: Build-time optimization and zero runtime overhead
- **Type safety**: Full TypeScript integration with generated types
- **Flexibility**: Framework-agnostic with multiple integration points
- **Developer experience**: Autocomplete, helpful errors, and visual tools

The system is designed to scale from small projects to large monorepos while maintaining fast build times and excellent
developer experience.
