# DOCX Templater - Product Specification
**Version:** 0.1.0 (Pre-implementation)
**Document Date:** 2026-08-13
**Status:** Design Specification
**Target Version:** 1.0.0
---
## Document Scope
This specification describes the complete functional and technical requirements for `docx-templating`, a Rust library providing template-based document generation for `.docx` (Microsoft Word) files.
**What This Document Covers:**
- Complete functional capabilities (user stories)
- Business rules and invariants
- Technical architecture and constraints
- Quality requirements (testing, performance, security)
- Implementation roadmap with prioritization
**What This Document Does NOT Cover:**
- Specific implementation details (class names, method signatures)
- Line-by-line code organization
- Deployment/distribution strategy beyond library publication
---
## Table of Contents
1. [System Overview](#system-overview)
2. [Functional Specifications](#functional-specifications)
3. [Business Rules & Invariants](#business-rules--invariants)
4. [Technical Architecture](#technical-architecture)
5. [Quality Requirements](#quality-requirements)
6. [Performance & Reliability](#performance--reliability)
7. [Security Requirements](#security-requirements)
8. [Implementation Roadmap](#implementation-roadmap)
9. [Open Questions](#open-questions)
---
## 1. System Overview
### 1.1 Purpose
`docx-templating` is a Rust library that enables developers to generate Microsoft Word documents (`.docx`) from templates with variable placeholders, conditional sections, and loops. It provides a Rust-native alternative to the Node.js `docxtemplater` library, with a focus on type safety, performance, and correctness.
### 1.2 Target Users
**Primary:** Rust developers building applications that need to generate formatted documents (invoices, reports, contracts, letters) from templates.
**Secondary:** Teams migrating from Node.js/JavaScript document generation to Rust ecosystems.
### 1.3 Core Value Proposition
- **Template-driven generation:** Designers create templates in Word, developers supply data
- **Type-safe data binding:** Rust structs serialize directly to template context
- **Correct DOCX output:** Generated documents open reliably in Microsoft Word
- **Safe by default:** No XML injection, automatic escaping, validation before rendering
### 1.4 High-Level Architecture
The crate is a pipeline with a pure core and two adapters around it:
```
┌──────────────────────────────────────────────┐
│ Public API │
│ Template, Context, IntoContext, │
│ RenderedDocument, TemplateOptions, Error │
└───────────────────┬──────────────────────────┘
│
┌───────────────────▼──────────────────────────┐
│ Adapters │
│ docx: parse and serialize WordprocessingML │
│ package: read and write the DOCX ZIP package │
└───────────────────┬──────────────────────────┘
│
┌───────────────────▼──────────────────────────┐
│ Domain (pure, no IO) │
│ document tree, binding, placement, │
│ resolved plan, evaluator │
└──────────────────────────────────────────────┘
```
**Design Principle:** The domain is the innermost layer and depends on nothing
outside `std`. The adapters depend on the domain and are the only place that
knows DOCX is XML inside a ZIP. The public API depends on both.
`tests/architecture.rs` enforces the boundary: nothing under `src/domain` may
reference `quick_xml`, `zip`, the filesystem, IO, or the adapters.
---
## 2. Functional Specifications
### 2.1 Template Loading
#### Story 2.1.1: Load Template from File Path
**As a** developer,
**I want** to load a DOCX template from a file path,
**So that** I can use existing template files stored on disk.
**Acceptance Criteria:**
- Given a valid file path to a `.docx` file
- When the template is loaded
- Then the DOCX package is validated
- And template syntax is parsed
- And errors are reported immediately (fail-fast)
- And the template is ready for rendering
**Error Cases:**
- File does not exist → `Io` error
- File is not a valid ZIP archive → `PackageError::MalformedArchive`
- Required DOCX parts are missing → `PackageError::MissingRequiredPart`
- Template syntax is invalid → `Placement(BindingError::Syntax)` with the part name and a span
---
#### Story 2.1.2: Load Template from Reader
**As a** developer,
**I want** to load a DOCX template from any `Read + Seek` source,
**So that** I can work with templates from HTTP streams, databases, or embedded resources.
**Acceptance Criteria:**
- Given a readable, seekable stream containing DOCX data
- When the template is loaded
- Then the template loads identically to file-based loading
- And the stream is consumed fully
- And resources are released properly
---
#### Story 2.1.3: Load Template from Byte Buffer
**As a** developer,
**I want** to load a DOCX template from a `Vec<u8>`,
**So that** I can work with in-memory template data.
**Acceptance Criteria:**
- Given a byte buffer containing valid DOCX data
- When the template is loaded
- Then the template loads without file system access
- And the buffer is not unnecessarily copied
---
### 2.2 Variable Replacement
#### Story 2.2.1: Replace Simple Variables
**As a** developer,
**I want** to replace placeholders like `{{name}}` with values from context,
**So that** I can generate personalized documents.
**Acceptance Criteria:**
- Given a template containing `{{variable}}`
- And a context with `{"variable": "value"}`
- When rendered
- Then all occurrences of `{{variable}}` are replaced with `"value"`
- And the replacement text is XML-escaped
- And original formatting is preserved
**Example:**
- Template: `Hello {{name}}!`
- Context: `{"name": "Ada Lovelace"}`
- Output: `Hello Ada Lovelace!`
---
#### Story 2.2.2: Replace Nested Object Properties
**As a** developer,
**I want** to access nested object properties using dot notation,
**So that** I can work with structured data.
**Acceptance Criteria:**
- Given a template containing `{{user.name}}`
- And a context with `{"user": {"name": "Grace Hopper"}}`
- When rendered
- Then `{{user.name}}` resolves to `"Grace Hopper"`
- And undefined paths are handled according to missing value policy
**Example:**
- Template: `Invoice for {{customer.name}} at {{customer.address.city}}`
- Context: `{"customer": {"name": "Ada", "address": {"city": "London"}}}`
- Output: `Invoice for Ada at London`
---
#### Story 2.2.3: Replace Array Element by Index
**As a** developer,
**I want** to access array elements using numeric indices,
**So that** I can reference specific items.
**Acceptance Criteria:**
- Given a template containing `{{items.0.name}}`
- And a context with `{"items": [{"name": "First"}, {"name": "Second"}]}`
- When rendered
- Then `{{items.0.name}}` resolves to `"First"`
---
#### Story 2.2.4: Handle Missing Values
**As a** developer,
**I want** to configure how missing values are handled,
**So that** I can control behavior when template data is incomplete.
**Acceptance Criteria:**
- Given a template containing `{{missing}}`
- And a context without `missing` field
- When rendered with policy `Empty`
- Then the placeholder is replaced with empty string
- When rendered with policy `KeepPlaceholder`
- Then the placeholder text remains unchanged
- When rendered with policy `Fail`
- Then a `RenderError::MissingValue` error is returned
---
### 2.3 Conditional Sections
#### Story 2.3.1: Show/Hide Content Based on Condition
**As a** developer,
**I want** to conditionally include or exclude document sections,
**So that** I can generate different content for different scenarios.
**Acceptance Criteria:**
- Given a template containing:
```
{% if customer.vip %}
VIP benefits apply
{% endif %}
```
- And a context with `{"customer": {"vip": true}}`
- When rendered
- Then the content between tags is included
- When context has `{"customer": {"vip": false}}`
- Then the content is removed
---
#### Story 2.3.2: Conditional with Else Branch
**As a** developer,
**I want** to show alternative content when a condition is false,
**So that** I can handle both cases.
**Acceptance Criteria:**
- Given a template containing:
```
{% if user.active %}
Welcome back!
{% else %}
Your account is inactive.
{% endif %}
```
- And a context with `{"user": {"active": true}}`
- When rendered
- Then only "Welcome back!" appears
- When context has `{"user": {"active": false}}`
- Then only "Your account is inactive." appears
---
#### Story 2.3.3: Negated Conditions
**As a** developer,
**I want** to test for false/absent values using `not`,
**So that** I can express negative conditions.
**Acceptance Criteria:**
- Given a template containing `{% if not user.disabled %}`
- And a context with `{"user": {"disabled": false}}`
- When rendered
- Then the block content is included
- When context has `{"user": {"disabled": true}}`
- Then the block content is excluded
---
#### Story 2.3.4: Else If Chains
**As a** developer,
**I want** to test several conditions in order,
**So that** mutually exclusive cases stay readable in one block.
**Acceptance Criteria:**
- Given a template containing:
```
{% if status == "open" %}
Open
{% elif status == "pending" %}
Pending
{% elif status == "closed" %}
Closed
{% else %}
Unknown
{% endif %}
```
- And a context with `{"status": "pending"}`
- When rendered
- Then only "Pending" appears
- And the chosen branch is the first condition that is true
- And a later branch that would fail on its own is never evaluated
- And an `elif` after `{% else %}` is rejected when the template loads
---
### 2.4 Loops
#### Story 2.4.1: Iterate Over Array Items
**As a** developer,
**I want** to repeat content for each item in an array,
**So that** I can generate tables, lists, and repeated sections.
**Acceptance Criteria:**
- Given a template containing:
```
{% for item in items %}
- {{item.name}}
{% endfor %}
```
- And a context with:
```json
{ "items": [{ "name": "Apple" }, { "name": "Banana" }] }
```
- When rendered
- Then two paragraphs are generated, one for each item
- And each iteration has its own scope with `item` bound
**Example Output:**
```
- Apple
- Banana
```
---
#### Story 2.4.2: Handle Empty Arrays
**As a** developer,
**I want** empty arrays to produce no output,
**So that** optional sections disappear when no data exists.
**Acceptance Criteria:**
- Given a template containing a for loop
- And a context with an empty array
- When rendered
- Then the template paragraph/row is removed
- And no placeholder artifacts remain
---
#### Story 2.4.3: Loop Over Primitives
**As a** developer,
**I want** to iterate over arrays of strings/numbers,
**So that** I can work with simple lists.
**Acceptance Criteria:**
- Given a template containing:
```
{% for tag in tags %}
{{.}}
{% endfor %}
```
- And a context with `{"tags": ["rust", "docx", "template"]}`
- When rendered
- Then each tag value is accessible via `.` (current item)
- And each tag value is also accessible through the loop variable, so `{{tag}}` and `{{.}}` render the same text
---
### 2.5 Table Operations
#### Story 2.5.1: Duplicate Table Rows
**As a** developer,
**I want** to place loop markers inside table rows,
**So that** I can generate dynamic tables.
**Acceptance Criteria:**
- Given a table template with loop markers in a row:
```
| {% for item in items %} {{item.sku}} | {{item.qty}} {% endfor %} |
```
- And a context with multiple items
- When rendered
- Then one table row is generated per item
- And table structure remains valid
- And cell formatting is preserved
---
#### Story 2.5.2: Conditional Table Rows
**As a** developer,
**I want** to conditionally include table rows,
**So that** I can show/hide rows based on data.
**Acceptance Criteria:**
- Given a table with conditional row markers
- When the condition is true
- Then the row appears
- When the condition is false
- Then the row is removed
- And the table remains structurally valid
---
### 2.6 Multi-Part Processing
#### Story 2.6.1: Process Headers and Footers
**As a** developer,
**I want** to apply templating to document headers and footers,
**So that** I can customize these sections per document.
**Acceptance Criteria:**
- Given a template with placeholders in header/footer parts
- And options configured with `headers_and_footers(true)`
- When rendered
- Then header and footer placeholders are replaced
- And main document is also processed
---
#### Story 2.6.2: Process Footnotes
**As a** developer,
**I want** to optionally process footnotes,
**So that** I can control which parts are templated.
**Acceptance Criteria:**
- Given a template with footnotes containing placeholders
- And options configured with footnotes enabled
- When rendered
- Then footnote content is templated
- When footnotes are disabled
- Then footnote parts are copied unchanged
---
### 2.7 Output Generation
#### Story 2.7.1: Generate In-Memory Document
**As a** developer,
**I want** to render templates to memory,
**So that** I can stream results or store them without file system access.
**Acceptance Criteria:**
- Given a rendered template
- When I call `.into_bytes()`
- Then I receive a complete DOCX file as `Vec<u8>`
- And the bytes represent a valid ZIP/DOCX archive
---
#### Story 2.7.2: Write Document to File
**As a** developer,
**I want** to save rendered documents directly to disk,
**So that** I have a convenient output method.
**Acceptance Criteria:**
- Given a rendered template
- When I call `.write_to_file(path)`
- Then the DOCX is written to the specified path
- And parent directories are created if needed
- And I/O errors are properly reported
---
#### Story 2.7.3: Write Document to Stream
**As a** developer,
**I want** to write rendered documents to any `Write` stream,
**So that** I can integrate with HTTP responses, pipes, or custom destinations.
**Acceptance Criteria:**
- Given a rendered template
- When I call `.write_to_writer(writer)`
- Then the complete DOCX is written to the stream
- And the writer is flushed
---
### 2.8 Context Creation
#### Story 2.8.1: Create Context from JSON Value
**As a** developer,
**I want** to create context from `serde_json::Value`,
**So that** I can work with dynamic data structures.
**Acceptance Criteria:**
- Given a `serde_json::Value` containing template data
- When I create a context from it
- Then path lookups resolve correctly
- And nested objects and arrays are accessible
---
#### Story 2.8.2: Create Context from Rust Structs
**As a** developer,
**I want** to create context from typed Rust structs,
**So that** I can leverage compile-time type safety.
**Acceptance Criteria:**
- Given a Rust struct implementing `Serialize`
- When I create context via `Context::from_serialize(&value)`
- Then the struct serializes to JSON internally
- And all fields are accessible in templates
- And serialization errors are reported
---
## 3. Business Rules & Invariants
### 3.1 Template Syntax Rules
**BR-001: Placeholder Delimiters**
Variable placeholders MUST use double curly braces: `{{expression}}`. Single braces are literal text.
**BR-002: Block Tag Delimiters**
Block tags (if, elif, for, else, endif, endfor) MUST use `{%` and `%}` delimiters.
**BR-003: Balanced Delimiters**
All opening delimiters (`{{`, `{%`) MUST have matching closing delimiters (`}}`, `%}`). Unclosed delimiters produce a `BindingError::Syntax` error that names the part and the span.
**BR-004: Block Nesting**
Block tags MUST be properly nested. `{% if %}` MUST close with `{% endif %}` before any outer block closes. Mismatched terminators produce a `BindingError::Syntax` error.
**BR-005: Else Placement**
`{% else %}` tags MUST appear only inside `{% if %}` blocks, after the if condition and before `{% endif %}`. Orphaned else tags produce syntax errors.
**BR-006: Filter Syntax**
A value expression MAY apply filters after a pipe: `{{name | upper}}`. A filter argument follows a colon as a quoted string or a bare token: `{{nickname | default: "friend"}}`, `{{amount | round: 2}}`. Filters may chain: `{{name | trim | upper}}`.
**BR-007: Filter Evaluation Order**
Filters apply left to right, each receiving the result of the one before it. An unregistered filter produces `RenderError::UnknownFilter`. A filter that rejects its value produces `RenderError::FilterFailed` with the reason. Both errors name the filter and the DOCX part.
**BR-008: Missing Values With Filters**
A missing path resolves to null when at least one filter is present, so `default` can supply a fallback. A bare missing path still follows `MissingValuePolicy`.
**BR-009: Number and Date Filters**
The built in number filters are `round`, `fixed`, `thousands` and `percent`. They accept a JSON number or a numeric string and report `RenderError::FilterFailed` for anything else. `round` takes an optional count of decimal places, defaulting to zero, and rounds half away from zero. `fixed` requires the count and returns text with exactly that many decimal places. `thousands` groups the integer digits in threes with an optional separator and does not round. `percent` takes an optional count, multiplies by 100 and appends `%`. With the `dates` feature on, `date` formats an ISO 8601 date, an instant or epoch seconds with a `strftime` pattern, and `timezone` converts an instant to an IANA zone or attaches a zone to a value without one. A value without an offset keeps its clock time, so attaching a zone does not shift it.
---
### 3.2 Path Resolution Rules
**BR-010: Dot Notation**
Path segments are separated by `.` (dot). `user.name` resolves as: get field "user", then get field "name" from the result.
**BR-011: Array Indexing**
Numeric path segments resolve as array indices. `items.0` accesses the first element of the `items` array.
**BR-012: Current Item Reference**
Inside a loop, `.` (single dot) refers to the current iteration value. The loop variable also refers to the same value, so `{% for item in items %}{{item}}{% endfor %}` renders an array of strings or numbers. When the element is an object, a field must be named, as in `{{item.name}}`; rendering the object itself produces `RenderError::CannotConvertToText` with the value type `object`.
**BR-013: Missing Field Behavior**
When a path segment does not exist, behavior depends on `MissingValuePolicy`:
- `Empty`: Replace with empty string
- `KeepPlaceholder`: Leave original placeholder text
- `Fail`: Return `RenderError::MissingValue` error
**BR-014: Type Mismatch Errors**
Attempting to access a field on a non-object value produces `RenderError::TypeMismatch` with expected vs. actual types.
**BR-015: Comparison Expressions**
A condition MAY compare two value expressions with `==`, `!=`, `<`, `<=`, `>`, `>=`: `{% if total > 100 %}`, `{% if status == "open" %}`. The operands may be paths, literals, filtered paths or parenthesized expressions. Equality compares any two values and treats numeric spellings of the same number as equal. Ordering compares two numbers or two strings; any other pairing produces `RenderError::InvalidComparison` naming both types. Comparisons are allowed in conditions only, so a comparison used as text or as a loop iterable produces `RenderError::ExpressionNotSupported`.
**BR-016: Boolean Logic**
A condition MAY combine expressions with `and`, `or`, `not` and parentheses: `{% if active and verified %}`, `{% if not (draft or revised) %}`. `not` binds tighter than `and`, and `and` binds tighter than `or`; parentheses override that order. `and` returns false and stops without evaluating its right side when the left side is falsy, and `or` returns true and stops when the left side is truthy, so a comparison that would fail on the skipped side never runs.
**BR-017: Arithmetic Expressions**
A placeholder or condition MAY compute with `+`, `-`, `*`, `/` and `%`: `{{price * quantity}}`, `{{(subtotal - discount) | fixed: 2}}`. `*`, `/` and `%` bind tighter than `+` and `-`, parentheses override that order, and a leading `-` negates a value. Both operands MUST be numbers; any other value produces `RenderError::ArithmeticType`, and division or remainder by zero produces `RenderError::DivisionByZero`. Integer operands produce an integer result when the operation is exact, so `{{2 * 3}}` writes `6` and `{{10 / 4}}` writes `2.5`. A filter written after an arithmetic expression applies to the whole result.
**BR-018: Else If Placement**
`{% elif expression %}` tags MUST appear only inside an `{% if %}` block, before that block's `{% else %}` tag, and MAY appear several times. The renderer tries the `if` condition first, then each `elif` in source order, then `else`, and keeps only the first true branch. Branches after the winning one are never evaluated. An `elif` with no open `if` produces `BindingError::UnexpectedTag`, and an `elif` after `{% else %}` produces `BindingError::MultipleTagsInBlock`.
---
### 3.3 Truthiness Rules
**BR-020: Falsy Values**
The following values are considered false in conditionals:
- `null`
- `false` (boolean)
- `0` (number)
- `""` (empty string)
- `[]` (empty array)
- `{}` (empty object)
**BR-021: Truthy Values**
All other values are considered true:
- `true` (boolean)
- Non-zero numbers
- Non-empty strings
- Non-empty arrays
- Non-empty objects
**BR-022: Negation**
The `not` operator inverts truthiness: `{% if not x %}` includes content when `x` is falsy.
---
### 3.4 XML Safety Rules
**BR-030: Mandatory Escaping**
All user-provided text MUST be XML-escaped before insertion. The following characters MUST be escaped:
- `<` → `<`
- `>` → `>`
- `&` → `&`
- `"` → `"`
- `'` → `'`
**BR-031: No Raw XML Injection**
Version 1.0 does NOT support raw XML injection. All text values are treated as plain text.
**BR-032: Whitespace Preservation**
When inserted text contains leading or trailing whitespace, the XML attribute `xml:space="preserve"` MUST be set on the containing text node.
---
### 3.5 Loop Rules
**BR-040: Iterable Types**
Loops MUST operate on array values. Attempting to loop over non-array values produces `RenderError::ExpectedIterable` error.
**BR-041: Empty Array Handling**
When looping over an empty array, the template paragraph/row MUST be removed entirely. No empty placeholder should remain.
**BR-042: Loop Scope**
Each loop iteration creates a new scope. The loop variable shadows any outer variable with the same name for the duration of the loop body.
**BR-043: Nested Loop Access**
Inner loops can access outer loop variables. Variable resolution checks innermost scope first, then outer scopes.
**BR-044: Loop Metadata**
Inside a loop, `@index`, `@first` and `@last` describe the current iteration. `@index` is zero based, `@first` is true on the first iteration and `@last` is true on the last one. The three values resolve in text, filters and conditions. They always refer to the innermost loop. A metadata name used outside a loop produces `RenderError::MetaOutsideLoop`, and an unknown name produces a render error that names it.
---
### 3.6 DOCX Structure Rules
**BR-050: Package Validation**
Every DOCX template MUST contain these required parts:
- `[Content_Types].xml`
- `_rels/.rels`
- `word/document.xml`
Missing required parts produce `PackageError::MissingRequiredPart` error.
**BR-051: Path Traversal Protection**
ZIP entries with path traversal sequences (`../`, absolute paths) MUST be rejected with `PackageError::UnsupportedEntry` error.
**BR-052: Block Placement Constraints**
Conditional and loop blocks MUST align with valid DOCX structural boundaries:
- Inline range within a paragraph
- Complete paragraph(s)
- Complete table row(s)
Blocks that cross unsupported boundaries produce `RenderError::UnsupportedBlockPlacement` error.
**BR-053: XML Well-Formedness**
Generated DOCX XML MUST remain well-formed after rendering. Malformed output is a bug, not a user error.
---
## 4. Technical Architecture
### 4.1 Layer Responsibilities
#### Public API
**Responsibility:** the surface a caller uses
**Modules:** `template`, `context`, `options`, `rendered`, `error`
**Capabilities:**
- Load a template from a path, a reader, bytes, or any `PackageSource`
- Accept a `Context`, a `serde_json::Value`, or any borrowed `serde::Serialize` value
- Render a resolved plan into a new DOCX package
- Report structured errors that name the failing part
**Key Types:**
- `Template<S = ZipPackageSource>` - a loaded template, rendered many times
- `Context` - the data a template is rendered against
- `IntoContext` - the conversion `Template::render` and the free `render` use
- `RenderedDocument` - the rendered package bytes
- `TemplateOptions` - policies for rendering
- `Error` - the top-level error enum
---
#### Adapters
**Responsibility:** translate between DOCX bytes and the domain model
**Modules:** `adapters::docx`, `adapters::package`, `package/`, `docx/`
**Capabilities:**
- Parse a WordprocessingML part into the lossless document tree
- Serialize the tree back, preserving untouched markup byte for byte
- Read and write the ZIP/OPC package
- Validate required parts and reject unsafe entry names
**Key Types:**
- `Document` - one parsed part: prolog, root and epilogue
- `Element`, `Node`, `TextNode` - the typed tree
- `PackageSource`, `PackageWriter` - package traits
- `ZipPackageSource`, `ZipPackageWriter`, `InMemoryPackageSource`
**Note:** `adapters::docx` and `adapters::package` are crate private. The
package traits and the part name helpers stay public because callers implement
and use them.
---
#### Domain
**Responsibility:** the document and template model, with no IO
**Modules:** `domain::document`, `domain::template`, `domain::binding`, `domain::placement`, `domain::plan`, `domain::engine`
**Capabilities:**
- Hold a lossless tree where unknown elements pass through untouched
- Project runs into logical text so a placeholder split across runs is seen whole
- Bind template tags to positions in that text
- Classify whether a block aligns with a paragraph, a row, or an inline range
- Evaluate the bound template against a context into a resolved plan
- Apply the plan to a copy of the tree
**Key Types:**
- `Document`, `Element`, `Role` - the tree
- `BoundTemplate`, `BoundParagraph`, `Block` - template positions
- `Plan`, `Edit` - the resolved edits
- `BindingError`, `PlanError`, `RenderError` - domain errors
**Design Decision:** Evaluation produces a resolved plan, and every loop
iteration carries its own nested plan. The renderer only applies edits. This
keeps evaluation testable without XML and keeps DOCX structure knowledge out of
the evaluator.
---
#### Template Syntax Parser
**Responsibility:** Template language processing
**Modules:** `syntax/`
**Capabilities:**
- Tokenize template syntax
- Parse tokens into an AST
- Validate block structure (matching tags, nesting)
- Report syntax errors with precise spans
- No dependency on DOCX concepts (testable with plain strings)
**Key Types:**
- `Node` enum - AST node (Text, Variable, If, For, Comment)
- `Expression` enum - Path or Not(Path)
- `Span` - source location inside one part
- `SyntaxError` - parse failure with a span and a message
**Note:** `syntax` is crate private. The binding layer calls it and turns a
`SyntaxError` into `BindingError::Syntax`, which carries the part name.
---
### 4.2 Data Flow
```
1. Load
├─ Read the ZIP archive (package adapter)
├─ Validate required parts exist (docx validation)
├─ Read word/document.xml
└─ Keep the headers, footers, footnotes and endnotes as bytes
2. Bind
├─ Parse the part into the lossless tree (docx adapter)
├─ Project runs into logical text (domain)
├─ Bind tags to positions, reject unsupported placements (domain)
└─ Repeat per secondary part when an option enables it
3. Render
├─ Evaluate the bound template against the context (domain engine)
├─ Produce a resolved plan with a nested plan per loop iteration (domain)
├─ Apply the plan to a copy of the tree (domain plan)
└─ Serialize the rendered part (docx adapter)
4. Write
├─ Write the rendered parts (package adapter)
└─ Copy every other part verbatim (package adapter)
```
---
### 4.3 Module Dependency Rules
**Allowed Dependencies:**
- Public API → Domain and Adapters
- Adapters → Domain
- Domain → `std` and the template syntax parser
**Forbidden Dependencies:**
- Domain MUST NOT depend on `quick_xml`, `zip`, the filesystem, IO, or the adapters
- Adapters MUST NOT depend on the public API
- The syntax parser MUST NOT depend on DOCX concepts
**Rationale:** the domain is testable with plain data, and the adapter boundary
is the only place that knows DOCX is XML inside a ZIP. `tests/architecture.rs`
enforces the first two rules on every test run.
---
### 4.4 Error Handling Architecture
**Top-Level Error:**
```rust
pub enum Error {
Io(std::io::Error),
Package(PackageError),
Xml(XmlError),
Placement(BindingError),
Plan(PlanError),
Render(RenderError),
Context(ContextError),
}
```
**Error Propagation:**
- Low-level modules return specific error types
- `From` implementations convert to the top-level `Error`
- All public API returns `Result<T, Error>`
- `Error::is_missing_value()` tells a missing field apart from a malformed
template
**Error Quality Requirements:**
- Include context (part name, span, path)
- Provide actionable messages
- Use `thiserror` for Display implementations
- Never panic on invalid user input
---
### 4.5 SOLID Principles Application
**Single Responsibility:**
- `domain::document` changes only for the tree model
- `domain::engine` changes only for evaluation
- `domain::plan` changes only for plan construction and application
- `adapters::docx` changes only for WordprocessingML parsing and serialization
- `package/` changes only for ZIP handling
- Each module has one reason to change
**Open/Closed:**
- Extend via traits (`PackageSource`, `PackageWriter`)
- No need to modify core `Template` for new sources
**Liskov Substitution:**
- Any `PackageSource` implementation is substitutable
- `ZipPackageSource` and `InMemoryPackageSource` behave identically from caller perspective
**Interface Segregation:**
- Small, focused traits (not one large trait)
- `PackageSource` separate from `PackageWriter`
**Dependency Inversion:**
- High-level `Template` depends on the `PackageSource` trait
- Not on the concrete `ZipPackageSource`
- The domain depends on its own types, not on XML or ZIP
- Enables testing with mock implementations
---
## 5. Quality Requirements
### 5.1 Testing Strategy
#### Test Pyramid
```
E2E Tests # Full Template::render() workflows
Fixture Tests # Real DOCX with golden outputs
Integration Tests # Multi-module interactions
Unit Tests # Isolated functions/modules
```
**Target Distribution:**
- Unit tests: 70% of test count
- Integration tests: 20%
- Fixture/E2E tests: 10%
---
#### Test Categories
**Unit Tests:**
- Parser with plain strings (no DOCX dependency)
- Path resolution against JSON values
- Truthiness rules
- XML escaping
- Text projection across split runs
- Loop scope behavior
**Integration Tests:**
- Parser + Context together
- Document tree + plan application
- Package + Rendering
**Fixture Tests:**
- Real `.docx` files in `tests/fixtures/`
- Each fixture includes:
- Input template DOCX
- Input context JSON
- Expected output (normalized XML or verification criteria)
**Golden Tests:**
- Snapshot testing with `insta` crate
- Compare normalized XML output against saved snapshots
- Normalize before comparison (whitespace, attribute order)
---
#### Phase-Specific Test Requirements
Each development phase has explicit test requirements:
**Phase 1 (Package):**
- Valid/invalid DOCX loading
- Part validation
- Path traversal rejection
- Unchanged part copying
**Phase 2 (XML):**
- Text plane from split runs
- Whitespace preservation
- Escaping correctness
- XML well-formedness
**Phase 3 (Parser):**
- AST generation
- Syntax error reporting with spans
- Block nesting validation
**Phase 4 (Context):**
- Path resolution (fields, arrays, nested)
- Truthiness rules
- Serialization from Rust structs
**Phase 5 (Inline Replacement):**
- End-to-end rendering
- Missing value policies
- Format preservation
- Split placeholder handling
**Phases 6-8 (Conditionals, Loops, Tables):**
- Block rendering
- Scope management
- Structure validation
- Edge cases (empty arrays, nested blocks)
---
### 5.2 Code Quality Standards
#### Linting Requirements
**Must Pass:**
```bash
cargo clippy --all-targets --all-features -- -D warnings
```
No clippy warnings allowed in CI.
**Key Clippy Rules:**
- No `unwrap()` or `expect()` in library code (except internal invariants)
- No panic paths on user input
- Prefer `?` for error propagation
- Use `#[must_use]` on `Result` types
---
#### Formatting Requirements
**Must Pass:**
```bash
cargo fmt --check
```
All code must be formatted with `rustfmt` defaults.
---
#### Documentation Requirements
**Public API:**
- All public items require rustdoc comments
- Include example code blocks
- Document error cases
- Link related types
**Modules:**
- Module-level documentation explaining purpose
- High-level architecture notes for complex modules
**Complex Logic:**
- Inline comments explaining "why", not "what"
- Cite relevant blueprint sections for design decisions
---
### 5.3 Definition of Done
A feature is complete when:
**Functional:**
- ✓ Implementation works as specified
- ✓ Edge cases handled explicitly
- ✓ Errors returned as `Result`, not panics
- ✓ Unsupported cases return clear errors
**Testing:**
- ✓ Unit tests exist for new logic
- ✓ Integration tests exist for user-visible behavior
- ✓ Fixture tests exist for DOCX-specific behavior
- ✓ Regression tests exist for every fixed bug
- ✓ All tests pass in CI
**Quality:**
- ✓ No clippy warnings
- ✓ Code is formatted
- ✓ No new unsafe code (unless justified)
- ✓ Public API reviewed for naming/design
**Documentation:**
- ✓ Public API has rustdoc
- ✓ Examples updated if needed
- ✓ CHANGELOG.md updated
- ✓ Known limitations documented
**CI:**
- ✓ All CI checks pass
- ✓ No failing tests
- ✓ Documentation builds successfully
---
### 5.4 Regression Prevention
**Every bug fix must include:**
1. A failing test that reproduces the bug
2. The fix implementation
3. Verification that the test now passes
4. Addition of test to regression suite
**Fixture-based bugs:**
- Add problematic DOCX to `tests/fixtures/regression/`
- Include context JSON
- Document expected behavior
- Add to CI suite
---
## 6. Performance & Reliability
### 6.1 Performance Targets
#### Version 1.0 Targets
**Document Size:**
- Support documents up to 100MB
- Support up to 10,000 placeholders per document
- Support up to 1,000 loop iterations per loop
**Memory:**
- Peak memory usage < 3x input document size
- No memory leaks (verify with Valgrind/sanitizers)
- Reuse allocations where possible (XML buffers)
**Throughput:**
- Process 1MB document with 100 placeholders in < 100ms (release build)
- Process 10MB document with 1,000 placeholders in < 500ms
- Baseline: modern desktop CPU (no specific hardware assumptions)
**Note:** These are targets, not guarantees. Version 1.0 prioritizes correctness over performance.
---
#### Performance Anti-Patterns to Avoid
**❌ Don't:**
- Decompress unchanged ZIP entries
- Parse entire XML into DOM when streaming suffices
- Clone context data unnecessarily
- Re-serialize user data multiple times
**✅ Do:**
- Stream unchanged ZIP entries directly to output
- Use event-based XML parsing with `quick-xml`
- Borrow into `serde_json::Value` during evaluation
- Buffer structural units (paragraphs, rows) only as needed
---
### 6.2 Scalability Considerations
#### Large Documents
**Challenges:**
- Memory pressure from large XML parts
- Many placeholders increase parsing time
- Deep nesting increases evaluation overhead
**Mitigation Strategies (Future):**
- Streaming API: `render_to_writer()` already provides foundation
- Chunk processing: process document in logical sections
- Lazy evaluation: defer context lookups until needed
**Version 1.0 Scope:**
- Focus on correct handling of medium-sized documents
- Document known limits
- Provide clear error messages on resource exhaustion
---
#### Large Arrays
**Challenges:**
- Looping over 10,000 items duplicates paragraph/row 10,000 times
- Memory allocation for duplicated XML
**Mitigation Strategies:**
- Use buffered writes instead of building entire output in memory
- Consider pagination recommendation in documentation
- Warn users about potential performance impact of large loops
---
### 6.3 Reliability Requirements
#### No Panics
**Requirement:** Library code MUST NOT panic on any user-provided input.
**Allowed Panics:**
- Internal invariant violations (use `debug_assert!` for checks)
- Panics in test code are acceptable
**Testing Strategy:**
- Fuzz testing with malformed inputs
- Property-based testing with arbitrary JSON
- Fixture tests with real-world DOCX files
---
#### Resource Cleanup
**Requirement:** All resources must be properly released.
**Resources to Track:**
- File handles (ZIP archives)
- Memory allocations
- Temporary buffers
**Testing Strategy:**
- Manual testing under resource constraints
- Verify no file handle leaks
- Run tests under sanitizers (LeakSanitizer)
---
#### Error Recovery
**Requirement:** Errors must leave the system in a clean state.
**Guarantees:**
- No partial writes (output is written atomically where possible)
- Failed renders do not corrupt input templates
- Clear error messages guide user to fix
---
### 6.4 Observability
#### Error Context
Every error must include sufficient context for debugging:
**Package Errors:**
- Part name that failed
- Expected vs. actual structure
**Syntax Errors:**
- Exact span (part, start, end)
- Offending text
- Suggestion for fix (when possible)
**Render Errors:**
- Template location (part, span)
- Data path that failed
- Expected vs. actual value type
**Example Error Output:**
```
Render error in word/document.xml:
expected iterable value at `items`, found object
Template location:
word/document.xml:142-178
{% for item in items %}
Context path:
items: {"type": "object"}
Suggestion:
Ensure `items` is an array, not an object
```
---
#### Logging
**Version 1.0 Scope:**
- No built-in logging (library should be silent by default)
- Errors contain all necessary information
- Future versions may add opt-in tracing with `tracing` crate
**Rationale:** Libraries should not force logging dependencies on users. Error types provide sufficient debugging information.
---
## 7. Security Requirements
### 7.1 Input Validation
#### ZIP Archive Validation
**Threat:** Malicious ZIP archives (zip bombs, path traversal)
**Mitigations:**
- **Path Traversal:** Reject entries with `../` or absolute paths
- **Size Limits:** Configurable maximum decompressed entry size
- **Entry Count:** Reasonable limit on number of entries
- **Compression Ratio:** Detect decompression bombs (high compression ratios)
**Implementation:**
- Validate all entry names before extraction
- Check decompressed size against limit
- Return `PackageError::UnsupportedEntry` for violations
---
#### XML Validation
**Threat:** Malformed XML causing parser vulnerabilities
**Mitigations:**
- Use well-tested parser (`quick-xml`)
- Fail gracefully on malformed XML
- Don't expose raw XML parsing errors to users (wrap in `XmlError`)
**Testing:**
- Fuzz XML parser with malformed inputs
- Test with real-world malformed DOCX files
---
### 7.2 XML Safety
#### Mandatory Escaping
**Requirement:** ALL user-provided text MUST be XML-escaped.
**Characters to Escape:**
```
< → <
> → >
& → &
" → "
' → '
```
**Implementation:**
- Use `quick-xml::escape::escape()` for text content
- Use `quick-xml::escape::escape_attribute()` for attributes
- Never construct XML via string concatenation
**Testing:**
- Test with special characters: `<script>`, `& Co`, `"quotes"`
- Property-based tests with arbitrary strings
- Verify output XML remains well-formed
---
#### No Raw XML Injection
**Decision:** Version 1.0 does NOT support raw XML injection.
**Rationale:**
- Prevents accidental XML injection vulnerabilities
- Simplifies security model
- Users who need this can use future opt-in `RawXml` type
**Future Consideration:**
```rust
pub struct RawXml(String); // Opt-in for advanced users
```
With explicit documentation warning about security implications.
---
### 7.3 Data Privacy
#### No Data Exfiltration
**Guarantee:** Library makes no network requests.
**Implementation:**
- No network dependencies
- No telemetry or analytics
- All processing is local
---
#### No Data Logging
**Guarantee:** Library does not log user context data.
**Implementation:**
- Error messages may reference paths/types but not values
- No `Debug` implementation on `Context` that exposes data
- Test fixtures use synthetic data only
---
### 7.4 Supply Chain Security
#### Dependency Auditing
**Requirement:** All dependencies must be audited regularly.
**Tools:**
```bash
cargo audit # Check for known vulnerabilities
cargo deny check # Check licenses and security advisories
```
**Policy:**
- Run `cargo audit` in CI
- Update dependencies on security advisories
- Prefer well-maintained crates from trusted authors
---
#### Minimal Dependencies
**Principle:** Depend on as few crates as possible.
**Core Dependencies (v1.0):**
- `zip` - ZIP archive handling
- `quick-xml` - XML parsing
- `serde` / `serde_json` - Data serialization
- `thiserror` - Error derivation
- `winnow` - Parser combinators
**Rationale:** Each dependency is a potential security risk. Keep the tree small and auditable.
---
### 7.5 Unsafe Code Policy
#### Default Position: No Unsafe
**Requirement:** Version 1.0 contains ZERO `unsafe` blocks.
**Rationale:**
- No compelling performance reason for unsafe in this domain
- Reduces audit surface
- Simplifies security review
**Future Exceptions:**
If future performance optimization requires unsafe:
- Must be isolated in private module
- Must be justified in design review
- Must document safety invariants
- Must be covered by targeted tests
- Ideally behind feature flag
---
### 7.6 Threat Model
#### In Scope
**Threats Library Defends Against:**
- Malicious ZIP archives (path traversal, bombs)
- XML injection via user data
- Malformed DOCX causing panics
- Resource exhaustion (memory, CPU)
#### Out of Scope
**Threats Library Does NOT Defend Against:**
- Physical access to machine running library
- Compromised Rust compiler/toolchain
- Side-channel attacks (timing, cache)
- Malicious code in user application
**Rationale:** Library focuses on data-level security. Infrastructure security is user's responsibility.
---
### 7.7 Security Testing
#### Fuzz Testing
**Targets:**
- Template parser with malformed syntax
- XML parser with malformed XML
- Context with arbitrary JSON
- ZIP reader with malicious archives
**Tools:**
- `cargo fuzz` with libFuzzer
- Property-based testing with `proptest`
**Goals:**
- No panics on arbitrary input
- No memory unsafety detected
- Graceful error handling
---
#### Adversarial Testing
**Test Cases:**
- Extremely deep nesting (10,000 levels)
- Very long strings (1GB)
- Huge arrays (1 million elements)
- Pathological regex patterns (if regex used)
- Unicode edge cases (emoji, RTL, combining characters)
**Expected Behavior:**
- Clear error messages
- No panics
- Bounded resource usage
---
## 8. Implementation Roadmap
### 8.1 Phased Delivery Strategy
**Guiding Principles:**
1. Each phase produces testable, usable increment
2. No phase builds on unstable foundation
3. Vertical slices over horizontal layers
4. Early phases deliver end-to-end value
---
### 8.2 Phase Breakdown
#### Phase 0: Engineering Baseline
**Goal:** Create healthy repository foundation
**Deliverables:**
- Cargo library scaffold
- CI pipeline (format, lint, test, docs)
- Test harness and fixture system
- Module layout skeleton
- Error type definitions
**Exit Criteria:**
- CI runs successfully
- Placeholder tests pass
- Team can add features without infrastructure changes
**Estimated Duration:** 1-2 days
---
#### Phase 1: Package Foundation
**Goal:** DOCX package reading/writing without templating
**Deliverables:**
- `PackageSource` trait
- `PackageWriter` trait
- ZIP-backed implementations
- In-memory package source (testing)
- DOCX validation
- Path traversal protection
**Key Test:** Open minimal DOCX, write it back, verify unchanged
**Exit Criteria:**
- Load valid DOCX from file/reader/bytes
- Reject invalid/malicious packages
- Write valid DOCX output
- All package tests pass
**Estimated Duration:** 1 week
---
#### Phase 2: XML Text Normalization
**Goal:** Extract and map DOCX text across split runs
**Deliverables:**
- Text projection across split runs
- Text span to node mapping
- XML escaping
- Basic text replacement (no template syntax yet)
**Key Challenge:** Handle `{{na` and `me}}` split across runs
**Exit Criteria:**
- Build logical text from XML
- Replace text spanning multiple nodes
- Preserve formatting and whitespace
- XML output remains well-formed
**Estimated Duration:** 1-2 weeks
---
#### Phase 3: Template Syntax Parser
**Goal:** Parse template syntax into AST
**Deliverables:**
- Lexer
- Parser
- AST types
- Span tracking
- Syntax error reporting
**Key Test:** Parse `"Hello {{name}}! {% if x %}Y{% endif %}"` correctly
**Exit Criteria:**
- Parse variables, conditionals, loops
- Report syntax errors with precise spans
- No dependency on DOCX (testable with strings)
- All parser tests pass
**Estimated Duration:** 1 week
---
#### Phase 4: Context and Data Lookup
**Goal:** Resolve template paths against data
**Deliverables:**
- `Context` type wrapping JSON
- Path resolution (dots, indices)
- Truthiness rules
- Serialization from Rust structs
**Key Test:** Resolve `user.items.0.name` against nested JSON
**Exit Criteria:**
- Resolve top-level, nested, array-indexed paths
- Implement truthiness rules
- Handle missing values per policy
- Create context from `serde::Serialize`
**Estimated Duration:** 1 week
---
#### Phase 5: Inline Variable Replacement (MVP)
**Goal:** First end-to-end feature - replace `{{variable}}`
**Deliverables:**
- Template orchestration
- Inline rendering
- Missing value policies
- End-to-end integration
**Key Test:** Load DOCX, render with context, write valid output
**Exit Criteria:**
- Complete example works end-to-end
- Split placeholders handled correctly
- Missing values handled per policy
- Generated DOCX opens in Word
**Version:** v0.1.0 (First Public Release)
**Estimated Duration:** 1-2 weeks
---
#### Phase 6: Conditionals
**Goal:** Support `{% if %}` blocks
**Deliverables:**
- Conditional evaluation
- Else branch support
- Paragraph-level block rendering
- Unsupported placement detection
**Key Test:** Show/hide paragraph based on boolean value
**Exit Criteria:**
- If/else rendering works
- Nested conditionals work
- Invalid placement returns error
- Generated XML remains valid
**Version:** v0.2.0
**Estimated Duration:** 1 week
---
#### Phase 7: Paragraph Loops
**Goal:** Support `{% for %}` over paragraphs
**Deliverables:**
- Loop evaluation
- Scope stack management
- Paragraph duplication
- Empty array handling
**Key Test:** Generate N paragraphs from N-element array
**Exit Criteria:**
- Paragraph loops work
- Empty arrays remove template paragraph
- Loop variables shadow outer scope
- Nested loops work (basic cases)
**Version:** v0.3.0
**Estimated Duration:** 1-2 weeks
---
#### Phase 8: Table Loops and Nested Blocks
**Goal:** Support table-row duplication
**Deliverables:**
- Table row detection
- Row duplication for loops
- Conditional rows
- Nested block validation
**Key Test:** Generate dynamic table from array
**Exit Criteria:**
- Table row loops work
- Cell formatting preserved
- Nested blocks work where structurally valid
- Invalid nesting returns error
**Version:** v0.4.0
**Estimated Duration:** 2 weeks
---
#### Phase 9: Multi-Part Support
**Goal:** Process headers, footers, footnotes
**Deliverables:**
- Part selection configuration
- Header/footer processing
- Footnote processing
- Options integration
**Key Test:** Replace placeholders in header and footer
**Exit Criteria:**
- Configurable part processing
- Headers and footers templated correctly
- Optional footnote processing works
- Main document + multi-part together
**Version:** v0.5.0
**Estimated Duration:** 1 week
---
#### Phase 10: Hardening and Performance
**Goal:** Production readiness
**Deliverables:**
- Fuzz testing
- Large document testing
- Performance benchmarks
- Error message improvements
- Dependency audit
**Key Activities:**
- Fuzz parser, XML handler, context
- Test with 100MB documents
- Benchmark rendering throughput
- Improve error context
- Remove all panics
**Exit Criteria:**
- No panics on fuzzed inputs
- Large documents handled gracefully
- Performance targets met or documented
- All errors have clear messages
- Security audit complete
**Version:** v0.8.0
**Estimated Duration:** 2 weeks
---
#### Phase 11: Release Candidate
**Goal:** API freeze and final polish
**Deliverables:**
- API review and stabilization
- Complete documentation
- Migration guide
- Example collection
- Final dependency updates
**Key Activities:**
- Review all public types for naming/design
- Write comprehensive examples
- Document limitations clearly
- Prepare docs.rs content
- Tag release candidate
**Exit Criteria:**
- No breaking API changes planned
- Documentation complete
- Examples all work
- No critical bugs
- Ready for early adopters
**Version:** v1.0.0-rc.1
**Estimated Duration:** 1 week
---
#### Phase 12: Stable 1.0 Release
**Goal:** Production-ready stable release
**Deliverables:**
- Final bug fixes
- Semantic versioning commitment
- Changelog finalization
- Publication to crates.io
**Post-Release Policy:**
- Patch releases for bug fixes (v1.0.x)
- Minor releases for backward-compatible features (v1.x.0)
- Major releases only for breaking changes (v2.0.0)
**Version:** v1.0.0
**Estimated Duration:** Final release milestone
---
### 8.3 Dependency Graph
```
Phase 0 (Baseline)
↓
Phase 1 (Package)
↓
Phase 2 (XML) ← Foundation for rendering
↓
├─→ Phase 3 (Parser) ← Can develop in parallel
└─→ Phase 4 (Context) ← Can develop in parallel
↓
Phase 5 (Inline Replacement) ← First MVP
↓
Phase 6 (Conditionals)
↓
Phase 7 (Paragraph Loops)
↓
Phase 8 (Table Loops)
↓
Phase 9 (Multi-Part)
↓
Phase 10 (Hardening)
↓
Phase 11 (RC)
↓
Phase 12 (v1.0)
```
---
### 8.4 Milestone Timeline
**Single Developer (Full-Time):**
- MVP (Phase 5): 4-6 weeks
- Conditionals + Loops (Phase 7): 7-9 weeks
- Full Feature Set (Phase 9): 12-14 weeks
- Production Ready (Phase 12): 16-20 weeks
**Small Team (2-3 Developers):**
- MVP: 3-4 weeks
- Full Feature Set: 8-10 weeks
- Production Ready: 12-16 weeks
**Parallelization Opportunities:**
- Phases 3 & 4 can develop simultaneously
- Fixture creation can happen during any phase
- Documentation can progress alongside implementation
---
### 8.5 Risk Management
#### High-Risk Areas
**1. Split Placeholders**
- **Risk:** Word splits text unpredictably
- **Mitigation:** Extensive fixture testing, logical text projection, golden tests
**2. Invalid DOCX Generation**
- **Risk:** Generated XML doesn't open in Word
- **Mitigation:** Constrained block model, validation, real Word testing
**3. Table Loops**
- **Risk:** Complex table structure duplication
- **Mitigation:** Start with simple row cases, reject ambiguous cases
**4. Performance**
- **Risk:** Large documents slow or memory-intensive
- **Mitigation:** Stream unchanged entries, benchmark early, document limits
---
## 9. Open Questions
### 9.1 Design Decisions Still Under Consideration
#### Q1: Arithmetic Expressions
**Question:** Should version 1.0 support arithmetic in templates?
```
{{item.price * item.quantity}}
```
**Pros:**
- Useful for invoices, calculations
- Common feature in template engines
**Cons:**
- Increases parser complexity
- Opens questions about operator precedence
- What about floating-point precision?
**Current Decision:** Implemented. Templates support `+`, `-`, `*`, `/`, `%` and unary minus with the usual precedence, as in `{{item.price * item.quantity}}` and `{% if subtotal - discount > 0 %}`. Both operands must be numbers, division by zero is a typed error, and integer results stay integers. Floating point follows `f64`, so a caller that needs decimal currency rounding should format the result with `fixed` or `round`.
---
#### Q2: Custom Filters/Helpers
**Question:** Should templates support filters like `{{name | uppercase}}`?
**Pros:**
- Common in templating languages (Liquid, Jinja2)
- Useful for formatting (dates, currency, case)
**Cons:**
- Requires plugin system
- Increases API surface area
- What's the standard library of filters?
**Current Decision:** Implemented. Templates support `{{name | upper}}` and custom filters registered on `TemplateOptions`. The built in filters are the text filters `upper`, `lower`, `trim`, `default`, `len` and `join`, the number filters `round`, `fixed`, `thousands` and `percent`, and the date filters `date` and `timezone` behind the default `dates` feature. A filter is a closure over the current value and its optional argument, so no separate trait object is required:
```rust
let options = TemplateOptions::default().filter("shout", |value, _| {
// transform value
});
```
**Future Consideration:** A currency filter and locale aware formatting can be added without changing the syntax. A filter that produces text for a specific locale can be registered by the caller today.
---
#### Q3: Image Replacement
**Question:** Should placeholders support image replacement?
```
{{company_logo}} → Replace with image file
```
**Pros:**
- Common use case (letterheads, reports)
- Other libraries support this
**Cons:**
- Requires relationship management (complex)
- Needs image format validation
- Different API from text replacement
**Current Decision:** NOT in v1.0. Focus on text templating first.
**Future Consideration:** v2.0 feature with explicit API:
```rust
context.insert_image("logo", ImageData::from_path("logo.png")?);
```
---
#### Q4: Streaming API
**Question:** Should library support streaming for very large documents?
**Pros:**
- Handles documents larger than RAM
- Lower memory footprint
**Cons:**
- More complex API
- May not align with parse-early philosophy
- Limits what can be validated upfront
**Current Decision:** v1.0 focuses on in-memory processing up to 100MB.
**Future Path:** `render_to_writer()` already exists as foundation for streaming in v2.0.
---
#### Q5: Dynamic Part Creation
**Question:** Should library support adding new parts (headers, images, etc.)?
**Pros:**
- Maximum flexibility
- Could support dynamic header generation
**Cons:**
- Very complex (relationships, content types)
- Easy to generate invalid DOCX
- Out of scope for "templating"
**Current Decision:** NOT in v1.0. Library templates existing parts only.
---
### 9.2 Implementation Questions
#### Q6: Parser Choice
**Question:** Use parser combinators (winnow) or hand-written parser?
**Considerations:**
- Parser combinators: maintainable, testable, but learning curve
- Hand-written: full control, potentially faster, more code
**Current Decision:** Use `winnow` (parser combinators) for:
- Maintainability
- Good error messages
- Community-standard approach
---
#### Q7: AST Representation
**Question:** Should AST be public or private?
**Pros of Public:**
- Advanced users can inspect parsed templates
- Enables analysis tools
**Cons of Public:**
- Locks in AST structure (semver commitment)
- May change between versions
**Current Decision:** PRIVATE in v1.0. Can expose in v2.0 if demand exists.
**Rationale:** Maintain flexibility to refactor AST without breaking changes.
---
#### Q8: Span Representation
**Question:** Should spans use byte offsets or line/column?
**Considerations:**
- Byte offsets: precise, compact
- Line/column: human-readable
**Current Decision:** Byte offsets internally, display as line/column in errors.
**Implementation:**
```rust
pub struct Span {
part: String, // "word/document.xml"
start: usize, // Byte offset
end: usize, // Byte offset
}
impl Display for Span {
// Convert to "word/document.xml:L42:C10-L42:C25"
}
```
---
### 9.3 Testing Questions
#### Q9: Fixture Coverage
**Question:** How many fixture DOCX files are sufficient?
**Current Plan:**
- Minimal (5-10 fixtures per feature)
- Focus on common cases and edge cases
- Real-world templates preferred over synthetic
**Categories:**
- Package: valid, invalid, corrupt (3-5 files)
- Inline: simple, split-run, special-chars (5-7 files)
- Conditional: if, if-else, nested (4-6 files)
- Loop: paragraph, table, empty, nested (6-8 files)
**Total Target:** 30-50 fixture DOCX files
---
#### Q10: Property Testing
**Question:** What properties should be tested?
**Candidates:**
- Parser: arbitrary safe strings don't panic
- Context: arbitrary JSON doesn't panic
- Escaping: escaped text is always valid XML
- Rendering: output DOCX is always valid ZIP
**Current Plan:**
- Start with parser and context (high ROI)
- Add escaping properties
- Add rendering properties in Phase 10
---
### 9.4 Performance Questions
#### Q11: Optimization Priority
**Question:** When should performance optimization begin?
**Current Decision:** After Phase 9 (multi-part support).
**Rationale:**
- Premature optimization risks
- Need stable API before optimizing
- Phase 10 dedicated to performance
**Benchmark Targets:**
- 1MB document, 100 placeholders: < 100ms
- 10MB document, 1000 placeholders: < 500ms
---
### 9.5 Documentation Questions
#### Q12: Example Depth
**Question:** How comprehensive should examples be?
**Current Plan:**
- README: Quick start (5-10 lines)
- Examples folder: 5-7 complete examples
- Basic variable replacement
- Invoice with table loop
- Conditional sections
- Nested loops
- Multi-part (header/footer)
- Error handling
- Custom source/writer
**Each Example Includes:**
- Commented code
- Sample template DOCX
- Sample context JSON
- Expected output description
---
### 9.6 API Design Questions
#### Q13: Builder Pattern Depth
**Question:** How much builder-style chaining should API support?
**Current Design:**
```rust
Template::from_path("template.docx")?
.with_options(
TemplateOptions::default()
.missing_value(MissingValuePolicy::Fail)
.headers_and_footers(true)
)
.render(context)?
.write_to_file("output.docx")?;
```
**Acceptable or too much chaining?**
**Current Decision:** This level is acceptable. Balances readability and convenience.
---
#### Q14: Error Granularity
**Question:** How fine-grained should error types be?
**Too Coarse:**
```rust
enum Error {
TemplateError(String), // Not helpful
}
```
**Too Fine:**
```rust
enum PackageError {
MissingContentTypes,
MissingRels,
MissingDocument,
MissingDocumentRels,
// ... 20 more variants
}
```
**Current Decision:** Mid-level granularity with context fields:
```rust
enum PackageError {
MissingRequiredPart(String), // Part name in field
UnsupportedEntry(String), // Entry name in field
// ...
}
```
---
### 9.7 Future Feature Considerations
#### Features Explicitly Deferred
**Not in v1.0, maybe v2.0+:**
- Image replacement
- Dynamic relationship management
- Chart data binding
- Content controls templating
- VBA macro support (likely never)
- Streaming very large documents
- Incremental rendering
- Template inheritance
- Partial templates
- Localization/i18n helpers
**Rationale:** Keep v1.0 focused on core text templating. Add features based on user demand.
---
## 10. Success Criteria
### 10.1 Version 1.0 Success Metrics
**Functional Completeness:**
- ✓ Load DOCX from file/reader/bytes
- ✓ Replace `{{variable}}` with nested path support
- ✓ Support `{% if %}` conditionals with `{% else %}`
- ✓ Support `{% for %}` loops over arrays
- ✓ Duplicate paragraphs and table rows
- ✓ Process headers and footers (optional)
- ✓ Safe XML escaping
- ✓ Clear error messages
**Quality Metrics:**
- ✓ 100% of public API documented
- ✓ 80%+ code coverage by tests
- ✓ Zero clippy warnings
- ✓ Zero unsafe code
- ✓ All CI checks pass
- ✓ No known panics on valid inputs
**Usability Metrics:**
- ✓ Examples compile and run
- ✓ Quick start works in < 10 lines
- ✓ Generated DOCX opens in Microsoft Word
- ✓ Error messages are actionable
**Performance Metrics:**
- ✓ Process 1MB/100 placeholders in < 100ms
- ✓ No memory leaks
- ✓ Reasonable memory usage (< 3x input size)
---
### 10.2 Post-Release Success
**Community Adoption:**
- Published on crates.io
- Documentation on docs.rs
- Example templates available
- Issue tracker active
**Maintenance Commitment:**
- Security patches within 48 hours
- Bug fixes in patch releases
- Feature requests triaged
- Semantic versioning respected
---
## 11. References
**External References:**
- DOCX Standard: ISO/IEC 29500 (Office Open XML)
- ZIP Format: PKWARE .ZIP File Format Specification
- Node.js docxtemplater: https://docxtemplater.com/
**Rust Crate Documentation:**
- `zip`: https://docs.rs/zip/
- `quick-xml`: https://docs.rs/quick-xml/
- `serde`: https://docs.rs/serde/
- `winnow`: https://docs.rs/winnow/
- `thiserror`: https://docs.rs/thiserror/
---
## Document History
| Version | Date | Author | Changes |
| ------- | ---------- | ------ | ------------------------------ |
| 0.1.0 | 2026-08-13 | AI | Initial specification creation |
---
**End of Specification**