From 9f74fddad070365feb14213409e4113454d20e9a Mon Sep 17 00:00:00 2001 From: atinseau Date: Thu, 12 Mar 2026 16:41:36 +0100 Subject: [PATCH] docs: migrate full documentation to dedicated docs/ directory --- README.md | 1709 +-------------------------------------- docs/advanced.md | 458 +++++++++++ docs/api-reference.md | 715 ++++++++++++++++ docs/error-handling.md | 294 +++++++ docs/execution.md | 186 +++++ docs/getting-started.md | 115 +++ docs/helpers.md | 578 +++++++++++++ docs/identifiers.md | 217 +++++ docs/schema-features.md | 238 ++++++ docs/static-analysis.md | 496 ++++++++++++ docs/templates.md | 366 +++++++++ 11 files changed, 3698 insertions(+), 1674 deletions(-) create mode 100644 docs/advanced.md create mode 100644 docs/api-reference.md create mode 100644 docs/error-handling.md create mode 100644 docs/execution.md create mode 100644 docs/getting-started.md create mode 100644 docs/helpers.md create mode 100644 docs/identifiers.md create mode 100644 docs/schema-features.md create mode 100644 docs/static-analysis.md create mode 100644 docs/templates.md diff --git a/README.md b/README.md index 80e5ec2..2df2b21 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ **Type-safe Handlebars template engine with static analysis powered by JSON Schema.** Typebars wraps Handlebars with a static analysis layer that validates your templates against a JSON Schema **before execution**. Given an input schema describing your data, Typebars detects unknown properties, type mismatches, and missing arguments at analysis time — and infers the exact JSON Schema of the template's output. + ```ts import { Typebars } from "typebars"; @@ -17,71 +18,19 @@ const inputSchema = { required: ["name", "age"], }; -// Analyze: validates the template against the input schema -// and infers the output schema +// Static analysis — no data needed const { valid, diagnostics, outputSchema } = engine.analyze( "Hello {{name}}, you are {{age}}!", inputSchema, ); -valid; // true — every referenced variable exists in the schema +valid; // true — every referenced variable exists outputSchema; // { type: "string" } — mixed template always produces a string -// Now analyze a single expression -const result = engine.analyze("{{age}}", inputSchema); -result.outputSchema; // { type: "number" } — inferred from the input schema - +// Execution — types are preserved +engine.execute("{{age}}", { name: "Alice", age: 30 }); // → 30 (number, not string) ``` -The output schema is inferred **statically** from the template structure and the input schema — no data is needed. - ---- - -## Table of Contents - -- [Installation](#installation) -- [Quick Start](#quick-start) -- [How It Works](#how-it-works) -- [Static Analysis — Input Validation](#static-analysis--input-validation) - - [Property Validation](#property-validation) - - [Nested Properties (Dot Notation)](#nested-properties-dot-notation) - - [Validation Inside Block Helpers](#validation-inside-block-helpers) - - [Diagnostics](#diagnostics) -- [Static Analysis — Output Schema Inference](#static-analysis--output-schema-inference) - - [Single Expression → Resolved Type](#single-expression--resolved-type) - - [Mixed Template → String](#mixed-template--string) - - [Single Block → Branch Type Inference](#single-block--branch-type-inference) - - [Object Templates → Object Schema](#object-templates--object-schema) - - [Literal Inputs → Primitive Schema](#literal-inputs--primitive-schema) -- [Schema Features](#schema-features) - - [`$ref` Resolution](#ref-resolution) - - [Combinators (`allOf`, `anyOf`, `oneOf`)](#combinators-allof-anyof-oneof) - - [`additionalProperties`](#additionalproperties) - - [Array `.length` Intrinsic](#array-length-intrinsic) -- [Execution & Type Preservation](#execution--type-preservation) -- [Compiled Templates](#compiled-templates) -- [Object Templates](#object-templates) -- [Block Helpers](#block-helpers) - - [`{{#if}}` / `{{#unless}}`](#if--unless) - - [`{{#each}}`](#each) - - [`{{#with}}`](#with) -- [Built-in Math Helpers](#built-in-math-helpers) -- [Built-in Logical & Comparison Helpers](#built-in-logical--comparison-helpers) - - [Why Sub-Expressions?](#why-sub-expressions) - - [Comparison Helpers](#comparison-helpers) - - [Equality Helpers](#equality-helpers) - - [Logical Operators](#logical-operators) - - [Generic `compare` Helper](#generic-compare-helper) - - [Nested Sub-Expressions](#nested-sub-expressions) - - [Static Analysis of Sub-Expressions](#static-analysis-of-sub-expressions) -- [Custom Helpers](#custom-helpers) - - [`registerHelper`](#registerhelper) - - [`defineHelper` (Type-Safe)](#definehelper-type-safe) -- [Template Identifiers (`{{key:N}}`)](#template-identifiers-keyn) -- [Output Type Coercion (`coerceSchema`)](#output-type-coercion-coerceschema) -- [Error Handling](#error-handling) -- [Configuration & API Reference](#configuration--api-reference) - --- ## Installation @@ -100,1626 +49,38 @@ bun add typebars --- -## Quick Start - -```ts -import { Typebars } from "typebars"; - -const engine = new Typebars(); - -const schema = { - type: "object", - properties: { - name: { type: "string" }, - age: { type: "number" }, - }, - required: ["name", "age"], -}; - -const data = { name: "Alice", age: 30 }; - -// 1. Analyze — validate + infer output type -const analysis = engine.analyze("Hello {{name}}", schema); -// analysis.valid → true -// analysis.outputSchema → { type: "string" } - -// 2. Execute — render the template -const result = engine.execute("Hello {{name}}", data); -// result → "Hello Alice" - -// 3. Or do both at once -const { analysis: a, value } = engine.analyzeAndExecute("{{age}}", schema, data); -// a.outputSchema → { type: "number" } -// value → 30 -``` - ---- - -## How It Works - -Typebars operates in three phases: - -``` - ┌────────────────────────────────────────────┐ - │ Input Schema │ - │ (JSON Schema describing available data) │ - └──────────────────┬─────────────────────────┘ - │ -┌──────────────┐ ┌───────────────────▼─────────────────────────┐ -│ Template │───▶│ Static Analyzer │ -│ (string) │ │ │ -└──────────────┘ │ 1. Validates every {{expression}} against │ - │ the input schema │ - │ 2. Validates block helper usage (#if on │ - │ existing property, #each on arrays...) │ - │ 3. Infers the output JSON Schema from the │ - │ template structure │ - │ │ - └──────┬───────────────────┬──────────────────┘ - │ │ - ┌────────────▼──┐ ┌──────────▼──────────┐ - │ Diagnostics │ │ Output Schema │ - │ (errors, │ │ (JSON Schema of │ - │ warnings) │ │ the return value) │ - └───────────────┘ └─────────────────────┘ -``` - -The **input schema** describes what variables are available. The **output schema** describes what the template will produce. The analyzer derives the output from the input — purely statically, without executing anything. - ---- - -## Static Analysis — Input Validation - -### Property Validation - -Every `{{expression}}` in the template is validated against the input schema. If a property doesn't exist, Typebars reports an error with the available properties: - -```ts -const schema = { - type: "object", - properties: { - name: { type: "string" }, - age: { type: "number" }, - }, -}; - -// ✅ Valid — "name" exists in the schema -engine.analyze("{{name}}", schema); -// → { valid: true, diagnostics: [] } - -// ❌ Invalid — "firstName" does not exist -engine.analyze("{{firstName}}", schema); -// → { -// valid: false, -// diagnostics: [{ -// severity: "error", -// code: "UNKNOWN_PROPERTY", -// message: 'Property "firstName" does not exist in the context schema. Available properties: age, name', -// details: { path: "firstName", availableProperties: ["age", "name"] } -// }] -// } - -// Multiple errors are reported at once -engine.analyze("{{foo}} and {{bar}}", schema); -// → 2 diagnostics, one for "foo" and one for "bar" -``` - -### Nested Properties (Dot Notation) - -Dot notation is validated at every depth level: - -```ts -const schema = { - type: "object", - properties: { - address: { - type: "object", - properties: { - city: { type: "string" }, - zip: { type: "string" }, - }, - }, - metadata: { - type: "object", - properties: { - role: { type: "string", enum: ["admin", "user", "guest"] }, - }, - }, - }, -}; - -// ✅ Valid — full path resolved -engine.analyze("{{address.city}}", schema); // valid: true -engine.analyze("{{metadata.role}}", schema); // valid: true - -// ❌ Invalid — "country" doesn't exist inside "address" -engine.analyze("{{address.country}}", schema); -// → error: Property "address.country" does not exist -``` - -### Validation Inside Block Helpers - -The analyzer walks **into** block helpers and validates every expression in every branch: - -```ts -const schema = { - type: "object", - properties: { - active: { type: "boolean" }, - name: { type: "string" }, - tags: { type: "array", items: { type: "string" } }, - orders: { - type: "array", - items: { - type: "object", - properties: { - id: { type: "number" }, - product: { type: "string" }, - }, - }, - }, - address: { - type: "object", - properties: { - city: { type: "string" }, - }, - }, - }, -}; - -// ✅ #if — validates the condition AND both branches -engine.analyze("{{#if active}}{{name}}{{else}}unknown{{/if}}", schema); -// valid: true - -// ❌ #if — invalid properties inside branches are caught -engine.analyze("{{#if active}}{{badProp1}}{{else}}{{badProp2}}{{/if}}", schema); -// valid: false — 2 errors (one per branch) - -// ❌ #if — invalid condition is caught -engine.analyze("{{#if nonexistent}}yes{{/if}}", schema); -// valid: false — "nonexistent" doesn't exist - -// ✅ #each — validates that the target is an array, then validates -// the body against the item schema -engine.analyze("{{#each orders}}{{product}} #{{id}}{{/each}}", schema); -// valid: true — "product" and "id" exist in the item schema - -// ❌ #each — property doesn't exist in the item schema -engine.analyze("{{#each orders}}{{badField}}{{/each}}", schema); -// valid: false — "badField" doesn't exist in order items - -// ❌ #each — target is not an array -engine.analyze("{{#each name}}{{this}}{{/each}}", schema); -// valid: false — TYPE_MISMATCH: "{{#each}}" expects array, got "string" - -// ✅ #with — changes context to a sub-object, validates inner expressions -engine.analyze("{{#with address}}{{city}}{{/with}}", schema); -// valid: true - -// ❌ #with — property doesn't exist in the sub-context -engine.analyze("{{#with address}}{{country}}{{/with}}", schema); -// valid: false — "country" doesn't exist inside "address" - -// ✅ Nested blocks — validated at every level -engine.analyze( - "{{#with address}}{{city}}{{/with}} — {{#each tags}}{{this}}{{/each}}", - schema, -); -// valid: true -``` - -**Key insight:** `{{#each}}` changes the schema context to the array's `items` schema. Inside `{{#each orders}}`, the context becomes `{ type: "object", properties: { id, product } }`. Inside `{{#each tags}}`, the context becomes `{ type: "string" }` and `{{this}}` refers to each string element. - -`{{#with}}` changes the schema context to the resolved sub-object schema. Inside `{{#with address}}`, the context becomes the schema of `address`. - -### Diagnostics - -Every diagnostic is a structured object with machine-readable fields: - -```ts -interface TemplateDiagnostic { - severity: "error" | "warning"; - code: DiagnosticCode; - message: string; - loc?: { - start: { line: number; column: number }; - end: { line: number; column: number }; - }; - source?: string; - details?: { - path?: string; - helperName?: string; - expected?: string; - actual?: string; - availableProperties?: string[]; - identifier?: number; - }; -} -``` - -Available diagnostic codes: - -| Code | Severity | Description | -|------|----------|-------------| -| `UNKNOWN_PROPERTY` | error | Property doesn't exist in the schema | -| `TYPE_MISMATCH` | error | Incompatible type (e.g. `{{#each}}` on a non-array) | -| `MISSING_ARGUMENT` | error | Block helper used without required argument | -| `UNKNOWN_HELPER` | warning | Unknown block helper | -| `UNANALYZABLE` | warning | Expression can't be statically analyzed | -| `MISSING_IDENTIFIER_SCHEMAS` | error | `{{key:N}}` used but no identifier schemas provided | -| `UNKNOWN_IDENTIFIER` | error | Identifier N not found in identifier schemas | -| `IDENTIFIER_PROPERTY_NOT_FOUND` | error | Property doesn't exist in identifier's schema | -| `PARSE_ERROR` | error | Invalid Handlebars syntax | - ---- - -## Static Analysis — Output Schema Inference - -This is where Typebars shines. Given a template and an input schema, Typebars **infers the JSON Schema of the output value**. The inferred type depends on the template structure. - -### Single Expression → Resolved Type - -When the template is a single `{{expression}}` (with optional whitespace around it), the output schema is the resolved type from the input schema: - -```ts -const schema = { - type: "object", - properties: { - name: { type: "string" }, - age: { type: "number" }, - score: { type: "integer" }, - active: { type: "boolean" }, - address: { - type: "object", - properties: { - city: { type: "string" }, - zip: { type: "string" }, - }, - }, - tags: { - type: "array", - items: { type: "string" }, - }, - role: { type: "string", enum: ["admin", "user", "guest"] }, - }, -}; - -engine.analyze("{{name}}", schema).outputSchema; -// → { type: "string" } - -engine.analyze("{{age}}", schema).outputSchema; -// → { type: "number" } - -engine.analyze("{{score}}", schema).outputSchema; -// → { type: "integer" } - -engine.analyze("{{active}}", schema).outputSchema; -// → { type: "boolean" } - -engine.analyze("{{address}}", schema).outputSchema; -// → { type: "object", properties: { city: { type: "string" }, zip: { type: "string" } } } - -engine.analyze("{{tags}}", schema).outputSchema; -// → { type: "array", items: { type: "string" } } - -// Dot notation resolves to the leaf type -engine.analyze("{{address.city}}", schema).outputSchema; -// → { type: "string" } - -// Enums are preserved -engine.analyze("{{role}}", schema).outputSchema; -// → { type: "string", enum: ["admin", "user", "guest"] } - -// Whitespace around a single expression is ignored -engine.analyze(" {{age}} ", schema).outputSchema; -// → { type: "number" } -``` - -**This is the key mechanism**: the output schema is **derived from** the input schema by resolving the expression path. `{{age}}` in a schema where `age` is `{ type: "number" }` produces an output schema of `{ type: "number" }`. - -### Mixed Template → String - -When a template contains text **and** expressions, or multiple expressions, the output is always `{ type: "string" }` — because Handlebars concatenates everything into a string: - -```ts -engine.analyze("Hello {{name}}", schema).outputSchema; -// → { type: "string" } - -engine.analyze("{{name}} ({{age}})", schema).outputSchema; -// → { type: "string" } - -engine.analyze("Just plain text", schema).outputSchema; -// → { type: "string" } -``` - -### Single Block → Branch Type Inference - -When the template is a **single block** (optionally surrounded by whitespace), Typebars infers the type from the block's branches: - -```ts -// Both branches are numeric literals → output is number -engine.analyze("{{#if active}}10{{else}}20{{/if}}", schema).outputSchema; -// → { type: "number" } - -// Both branches are booleans → output is boolean -engine.analyze("{{#if active}}true{{else}}false{{/if}}", schema).outputSchema; -// → { type: "boolean" } - -// Both branches are single expressions of the same type → that type -engine.analyze( - "{{#if active}}{{name}}{{else}}{{address.city}}{{/if}}", - schema, -).outputSchema; -// → { type: "string" } -// (both are string, so the output is string) - -// Branches with different types → oneOf union -engine.analyze( - "{{#if active}}{{age}}{{else}}{{score}}{{/if}}", - schema, -).outputSchema; -// → { oneOf: [{ type: "number" }, { type: "integer" }] } - -engine.analyze( - "{{#if active}}42{{else}}hello{{/if}}", - schema, -).outputSchema; -// → { oneOf: [{ type: "number" }, { type: "string" }] } - -// null in one branch → union with null -engine.analyze( - "{{#if active}}null{{else}}fallback{{/if}}", - schema, -).outputSchema; -// → { oneOf: [{ type: "null" }, { type: "string" }] } - -// #unless works the same way -engine.analyze( - "{{#unless active}}0{{else}}1{{/unless}}", - schema, -).outputSchema; -// → { type: "number" } - -// #with as single block → type of the inner body -engine.analyze("{{#with address}}{{city}}{{/with}}", schema).outputSchema; -// → { type: "string" } - -// #each always produces string (concatenation of iterations) -engine.analyze("{{#each tags}}{{this}}{{/each}}", schema).outputSchema; -// → { type: "string" } -``` - -The inference logic per block type: - -| Block | Output Schema | -|-------|---------------| -| `{{#if}}` with else | `oneOf(then_type, else_type)` (simplified if both are equal) | -| `{{#if}}` without else | Type of the then branch | -| `{{#unless}}` | Same as `{{#if}}` (inverted semantics, same type inference) | -| `{{#each}}` | Always `{ type: "string" }` (concatenation) | -| `{{#with}}` | Type of the inner body | - -### Object Templates → Object Schema - -When you pass an object as a template, each property is analyzed independently and the output schema is an object schema: - -```ts -const schema = { - type: "object", - properties: { - name: { type: "string" }, - age: { type: "number" }, - city: { type: "string" }, - }, -}; - -const analysis = engine.analyze( - { - userName: "Hello {{name}}!", // mixed → string - userAge: "{{age}}", // single expression → number - location: "{{city}}", // single expression → string - }, - schema, -); - -analysis.outputSchema; -// → { -// type: "object", -// properties: { -// userName: { type: "string" }, -// userAge: { type: "number" }, -// location: { type: "string" }, -// }, -// required: ["userName", "userAge", "location"], -// } -``` - -Nesting works recursively: - -```ts -engine.analyze( - { - user: { - name: "{{name}}", - age: "{{age}}", - }, - meta: { - active: "{{active}}", - }, - }, - schema, -).outputSchema; -// → { -// type: "object", -// properties: { -// user: { -// type: "object", -// properties: { -// name: { type: "string" }, -// age: { type: "number" }, -// }, -// required: ["name", "age"], -// }, -// meta: { -// type: "object", -// properties: { -// active: { type: "boolean" }, -// }, -// required: ["active"], -// }, -// }, -// required: ["user", "meta"], -// } -``` - -If **any** property in the object template is invalid, the entire object is marked as `valid: false` and all diagnostics are collected. - -### Literal Inputs → Primitive Schema - -Non-string values (`number`, `boolean`, `null`) are treated as passthrough literals. They are always valid (the input schema is ignored) and their output schema is inferred from the value: - -```ts -engine.analyze(42, schema).outputSchema; -// → { type: "integer" } - -engine.analyze(3.14, schema).outputSchema; -// → { type: "number" } - -engine.analyze(true, schema).outputSchema; -// → { type: "boolean" } - -engine.analyze(null, schema).outputSchema; -// → { type: "null" } -``` - -This is useful in object templates where some properties are fixed values: - -```ts -engine.analyze( - { - name: "{{name}}", // → string (from schema) - version: 42, // → integer (literal) - isPublic: true, // → boolean (literal) - deleted: null, // → null (literal) - }, - schema, -).outputSchema; -// → { -// type: "object", -// properties: { -// name: { type: "string" }, -// version: { type: "integer" }, -// isPublic: { type: "boolean" }, -// deleted: { type: "null" }, -// }, -// required: ["name", "version", "isPublic", "deleted"], -// } -``` - ---- - -## Schema Features - -### `$ref` Resolution - -Internal `$ref` references (`#/definitions/...`) are resolved transparently: - -```ts -const schema = { - type: "object", - definitions: { - Address: { - type: "object", - properties: { - street: { type: "string" }, - city: { type: "string" }, - }, - }, - }, - properties: { - home: { $ref: "#/definitions/Address" }, - work: { $ref: "#/definitions/Address" }, - }, -}; - -// ✅ Resolves through $ref -engine.analyze("{{home.city}}", schema); - -// → valid: true, outputSchema: { type: "string" } - -// ✅ Works with multiple $ref to the same definition -engine.analyze("{{home.city}} — {{work.street}}", schema); -// → valid: true - -// ❌ Property doesn't exist behind the $ref -engine.analyze("{{home.zip}}", schema); -// → valid: false — "zip" not found in Address -``` - -Nested `$ref` (a `$ref` pointing to another `$ref`) is resolved recursively. - -### Combinators (`allOf`, `anyOf`, `oneOf`) - -Properties defined across combinators are resolved: - -```ts -const schema = { - type: "object", - allOf: [ - { type: "object", properties: { a: { type: "string" } } }, - { type: "object", properties: { b: { type: "number" } } }, - ], -}; - -engine.analyze("{{a}}", schema).valid; // true → { type: "string" } -engine.analyze("{{b}}", schema).valid; // true → { type: "number" } -``` - -`oneOf` and `anyOf` branches are also searched. - -### `additionalProperties` - -When a property isn't found in `properties` but `additionalProperties` is set: - -```ts -// additionalProperties: true → any property is allowed (type unknown) -engine.analyze("{{anything}}", { type: "object", additionalProperties: true }); -// → valid: true, outputSchema: {} - -// additionalProperties with a schema → resolved to that schema -engine.analyze("{{anything}}", { - type: "object", - additionalProperties: { type: "number" }, -}); -// → valid: true, outputSchema: { type: "number" } - -// additionalProperties: false → unknown properties are rejected -engine.analyze("{{anything}}", { - type: "object", - properties: { name: { type: "string" } }, - additionalProperties: false, -}); -// → valid: false -``` - -### Array `.length` Intrinsic - -Accessing `.length` on an array is valid and inferred as `{ type: "integer" }`: - -```ts -const schema = { - type: "object", - properties: { - tags: { type: "array", items: { type: "string" } }, - orders: { type: "array", items: { type: "object", properties: { id: { type: "number" } } } }, - }, -}; - -engine.analyze("{{tags.length}}", schema).outputSchema; -// → { type: "integer" } - -engine.analyze("{{orders.length}}", schema).outputSchema; -// → { type: "integer" } - -// .length on a non-array is invalid -engine.analyze("{{name.length}}", { - type: "object", - properties: { name: { type: "string" } }, -}); -// → valid: false, code: UNKNOWN_PROPERTY -``` - ---- - -## Execution & Type Preservation - -Typebars preserves types at execution time. The behavior depends on the template structure: - -| Template Shape | Execution Return Type | -|---|---| -| Single expression `{{expr}}` | Raw value (`number`, `boolean`, `object`, `array`, `null`…) | -| Mixed template `text {{expr}}` | `string` (concatenation) | -| Single block with literal branches | Coerced value (`number`, `boolean`, `null`) | -| Multi-block or mixed | `string` | -| Literal input (`42`, `true`, `null`) | The value as-is | - -```ts -const engine = new Typebars(); -const data = { name: "Alice", age: 30, active: true, tags: ["ts", "js"] }; - -// Single expression → raw type -engine.execute("{{age}}", data); // → 30 (number) -engine.execute("{{active}}", data); // → true (boolean) -engine.execute("{{tags}}", data); // → ["ts", "js"] (array) - -// Mixed → string -engine.execute("Age: {{age}}", data); // → "Age: 30" (string) - -// Single block with literal branches → coerced -engine.execute("{{#if active}}42{{else}}0{{/if}}", data); // → 42 (number) -engine.execute("{{#if active}}true{{else}}false{{/if}}", data); // → true (boolean) - -// Literal passthrough -engine.execute(42, data); // → 42 -engine.execute(true, data); // → true -engine.execute(null, data); // → null -``` - -This means the **output schema** inferred at analysis time matches the actual runtime value type. - ---- - -## Compiled Templates - -For templates executed multiple times, `compile()` parses the template once and returns a reusable `CompiledTemplate`: - -```ts -const engine = new Typebars(); -const tpl = engine.compile("Hello {{name}}!"); - -// No re-parsing — execute many times -tpl.execute({ name: "Alice" }); // → "Hello Alice!" -tpl.execute({ name: "Bob" }); // → "Hello Bob!" - -// Analyze without re-parsing -tpl.analyze(schema); - -// Validate -tpl.validate(schema); - -// Both at once -const { analysis, value } = tpl.analyzeAndExecute(schema, data); -``` - -Object templates and literal values can also be compiled: - -```ts -const tpl = engine.compile({ - userName: "{{name}}", - userAge: "{{age}}", - fixed: 42, -}); - -tpl.execute(data); -// → { userName: "Alice", userAge: 30, fixed: 42 } - -tpl.analyze(schema).outputSchema; -// → { type: "object", properties: { userName: { type: "string" }, userAge: { type: "number" }, fixed: { type: "integer" } }, ... } -``` - ---- - -## Object Templates - -Pass an object where each property is a template. Every property is analyzed/executed independently: - -```ts -const engine = new Typebars(); +## Documentation -// Execute -const result = engine.execute( - { - greeting: "Hello {{name}}!", - userAge: "{{age}}", - tags: "{{tags}}", - fixed: 42, - nested: { - city: "{{address.city}}", - }, - }, - data, -); -// → { -// greeting: "Hello Alice!", -// userAge: 30, -// tags: ["ts", "js"], -// fixed: 42, -// nested: { city: "Paris" }, -// } - -// Validate — errors from ALL properties are collected -const analysis = engine.analyze( - { - ok: "{{name}}", - bad: "{{nonexistent}}", - }, - schema, -); -// analysis.valid → false (at least one property has an error) -// analysis.diagnostics → [{ ... "nonexistent" ... }] -``` - ---- - -## Block Helpers - -### `{{#if}}` / `{{#unless}}` - -Conditional rendering. The analyzer validates the condition and both branches. - -The condition can be a simple property reference **or a sub-expression** using one of the [built-in logical helpers](#built-in-logical--comparison-helpers): - -```ts -// Simple property condition -engine.execute("{{#if active}}Online{{else}}Offline{{/if}}", data); -// → "Online" - -engine.execute("{{#unless active}}No{{else}}Yes{{/unless}}", { active: false }); -// → "No" - -// Sub-expression condition (see "Built-in Logical & Comparison Helpers") -engine.execute( - "{{#if (gt age 18)}}Adult{{else}}Minor{{/if}}", - { age: 30 }, -); -// → "Adult" - -engine.execute( - '{{#if (eq role "admin")}}Full access{{else}}Limited{{/if}}', - { role: "admin" }, -); -// → "Full access" -``` - -> **Note:** Handlebars natively only supports simple property references as `{{#if}}` conditions (e.g. `{{#if active}}`). Sub-expression conditions like `{{#if (gt age 18)}}` are made possible by the logical helpers that Typebars pre-registers on every engine instance. See [Built-in Logical & Comparison Helpers](#built-in-logical--comparison-helpers) for details. - -### `{{#each}}` - -Iterates over arrays. The analyzer validates that the target is an array and switches the schema context to the item schema: - -```ts -engine.execute("{{#each tags}}{{this}} {{/each}}", data); -// → "ts js " - -engine.execute("{{#each orders}}#{{id}} {{product}} {{/each}}", { - orders: [ - { id: 1, product: "Keyboard" }, - { id: 2, product: "Mouse" }, - ], -}); -// → "#1 Keyboard #2 Mouse " - -// Nested #each -engine.execute( - "{{#each groups}}[{{#each members}}{{this}}{{/each}}]{{/each}}", - { groups: [{ members: ["a", "b"] }, { members: ["c"] }] }, -); -// → "[ab][c]" -``` - -### `{{#with}}` - -Changes the context to a sub-object. The analyzer switches the schema context: - -```ts -engine.execute("{{#with address}}{{city}}, {{zip}}{{/with}}", { - address: { city: "Paris", zip: "75001" }, -}); -// → "Paris, 75001" - -// Nested #with -engine.analyze( - "{{#with level1}}{{#with level2}}{{value}}{{/with}}{{/with}}", - { - type: "object", - properties: { - level1: { - type: "object", - properties: { - level2: { - type: "object", - properties: { value: { type: "string" } }, - }, - }, - }, - }, - }, -); -// → valid: true -``` - ---- - -## Built-in Math Helpers - -Pre-registered on every `Typebars` instance. All return `{ type: "number" }` for static analysis. - -### Named Operators - -| Helper | Aliases | Usage | Example | -|--------|---------|-------|---------| -| `add` | — | `{{add a b}}` | `{{add price tax}}` → 121 | -| `subtract` | `sub` | `{{sub a b}}` | `{{sub price discount}}` → 80 | -| `multiply` | `mul` | `{{mul a b}}` | `{{mul price quantity}}` → 300 | -| `divide` | `div` | `{{div a b}}` | `{{div total count}}` → 33.3 | -| `modulo` | `mod` | `{{mod a b}}` | `{{mod 10 3}}` → 1 | -| `pow` | — | `{{pow a b}}` | `{{pow 2 10}}` → 1024 | -| `min` | — | `{{min a b}}` | `{{min a b}}` → smaller | -| `max` | — | `{{max a b}}` | `{{max a b}}` → larger | - -### Unary Functions - -| Helper | Usage | Description | -|--------|-------|-------------| -| `abs` | `{{abs value}}` | Absolute value | -| `ceil` | `{{ceil value}}` | Round up | -| `floor` | `{{floor value}}` | Round down | -| `round` | `{{round value [precision]}}` | Round with optional decimal places | -| `sqrt` | `{{sqrt value}}` | Square root | - -```ts -engine.execute("{{round pi 2}}", { pi: 3.14159 }); // → 3.14 -engine.execute("{{abs value}}", { value: -7 }); // → 7 -engine.execute("{{div items.length count}}", { items: [1,2,3,4,5], count: 2 }); // → 2.5 -``` - -### Generic `math` Helper - -Inline arithmetic with the operator as a string: - -```ts -engine.execute('{{math a "+" b}}', { a: 10, b: 3 }); // → 13 -engine.execute('{{math a "*" b}}', { a: 10, b: 3 }); // → 30 -engine.execute('{{math a "**" b}}', { a: 2, b: 10 }); // → 1024 -``` - -Supported operators: `+`, `-`, `*`, `/`, `%`, `**` - -All math helpers are **fully integrated with static analysis** — they validate that parameters resolve to `{ type: "number" }` and infer `{ type: "number" }` as output: - -```ts -const schema = { - type: "object", - properties: { - a: { type: "number" }, - b: { type: "number" }, - label: { type: "string" }, - }, -}; - -// ✅ Valid -const { analysis, value } = engine.analyzeAndExecute( - "{{add a b}}", - schema, - { a: 10, b: 3 }, -); -analysis.outputSchema; // → { type: "number" } -value; // → 13 - -// ⚠️ Type mismatch on parameter -const { analysis: a2 } = engine.analyzeAndExecute( - "{{add a label}}", - schema, - { a: 10, label: "hello" }, -); -// a2.valid → false (string passed to a number parameter) -``` - ---- - -## Built-in Logical & Comparison Helpers - -Pre-registered on every `Typebars` instance. All return `{ type: "boolean" }` for static analysis. - -These helpers enable **conditional logic** inside templates via Handlebars [sub-expressions](https://handlebarsjs.com/guide/subexpressions.html) — the `(helper arg1 arg2)` syntax used as arguments to block helpers like `{{#if}}` and `{{#unless}}`. - -### Why Sub-Expressions? - -Standard Handlebars only supports simple truthiness checks: - -```handlebars -{{!-- Native Handlebars: can only test if "active" is truthy --}} -{{#if active}}yes{{else}}no{{/if}} -``` - -There is **no built-in way** to compare values, combine conditions, or negate expressions. Handlebars deliberately delegates this to helpers. - -Typebars ships a complete set of logical and comparison helpers that unlock expressive conditions out of the box: - -```handlebars -{{!-- Typebars: compare, combine, negate — all statically analyzed --}} -{{#if (gt age 18)}}adult{{else}}minor{{/if}} -{{#if (and active (eq role "admin"))}}full access{{/if}} -{{#if (not suspended)}}welcome{{/if}} -``` - -These helpers are **fully integrated with the static analyzer**: argument types are validated, missing properties are caught, and the output schema is correctly inferred from the branches — not from the boolean condition. - -### Comparison Helpers - -| Helper | Aliases | Usage | Description | -|--------|---------|-------|-------------| -| `lt` | — | `(lt a b)` | `a < b` (numeric) | -| `lte` | `le` | `(lte a b)` | `a <= b` (numeric) | -| `gt` | — | `(gt a b)` | `a > b` (numeric) | -| `gte` | `ge` | `(gte a b)` | `a >= b` (numeric) | - -Both parameters must resolve to `{ type: "number" }`. A type mismatch is reported as an error: - -```ts -const schema = { - type: "object", - properties: { - age: { type: "number" }, - score: { type: "number" }, - name: { type: "string" }, - account: { - type: "object", - properties: { balance: { type: "number" } }, - }, - }, -}; - -// ✅ Both arguments are numbers -engine.analyze("{{#if (lt age 18)}}minor{{else}}adult{{/if}}", schema); -// valid: true, no diagnostics - -// ✅ Nested property access works -engine.analyze("{{#if (lt account.balance 500)}}low{{else}}ok{{/if}}", schema); -// valid: true - -// ✅ Number literals are accepted -engine.analyze("{{#if (gte score 90)}}A{{else}}B{{/if}}", schema); -// valid: true - -// ❌ String where number is expected → TYPE_MISMATCH -engine.analyze("{{#if (lt name 500)}}yes{{/if}}", schema); -// valid: false — "name" is string, "lt" expects number -``` - -### Equality Helpers - -| Helper | Aliases | Usage | Description | -|--------|---------|-------|-------------| -| `eq` | — | `(eq a b)` | Strict equality (`===`) | -| `ne` | `neq` | `(ne a b)` | Strict inequality (`!==`) | - -These accept any type — no type constraint on parameters: - -```ts -// String comparison -engine.execute('{{#if (eq role "admin")}}yes{{else}}no{{/if}}', { role: "admin" }); -// → "yes" - -// Number comparison -engine.execute("{{#if (ne score 0)}}scored{{else}}zero{{/if}}", { score: 85 }); -// → "scored" -``` - -### Logical Operators - -| Helper | Usage | Description | -|--------|-------|-------------| -| `not` | `(not value)` | Logical negation — `true` if value is falsy | -| `and` | `(and a b)` | Logical AND — `true` if both are truthy | -| `or` | `(or a b)` | Logical OR — `true` if at least one is truthy | - -```ts -engine.execute("{{#if (not active)}}inactive{{else}}active{{/if}}", { active: false }); -// → "inactive" - -engine.execute( - "{{#if (and active premium)}}VIP{{else}}standard{{/if}}", - { active: true, premium: true }, -); -// → "VIP" - -engine.execute( - "{{#if (or isAdmin isModerator)}}staff{{else}}user{{/if}}", - { isAdmin: false, isModerator: true }, -); -// → "staff" -``` - -### Collection Helpers - -| Helper | Usage | Description | -|--------|-------|-------------| -| `contains` | `(contains haystack needle)` | `true` if the string contains the substring, or the array contains the element | -| `in` | `(in value ...candidates)` | `true` if value is one of the candidates (variadic) | - -```ts -engine.execute( - '{{#if (contains name "ali")}}match{{else}}no match{{/if}}', - { name: "Alice" }, -); -// → "match" - -engine.execute( - '{{#if (in status "active" "pending")}}ok{{else}}blocked{{/if}}', - { status: "active" }, -); -// → "ok" -``` - -### Generic `compare` Helper - -A single helper with the operator as a string parameter: - -```ts -engine.execute('{{#if (compare a "<" b)}}yes{{else}}no{{/if}}', { a: 3, b: 10 }); -// → "yes" - -engine.execute('{{#if (compare name "===" "Alice")}}hi Alice{{/if}}', { name: "Alice" }); -// → "hi Alice" -``` - -Supported operators: `==`, `===`, `!=`, `!==`, `<`, `<=`, `>`, `>=` - -### Nested Sub-Expressions - -Sub-expressions can be **nested** to build complex conditions. Each level is fully analyzed: - -```ts -// AND + comparison -engine.execute( - '{{#if (and (eq role "admin") (gt score 90))}}top admin{{else}}other{{/if}}', - { role: "admin", score: 95 }, -); -// → "top admin" - -// OR + NOT -engine.execute( - "{{#if (or (not active) (lt score 10))}}alert{{else}}ok{{/if}}", - { active: true, score: 85 }, -); -// → "ok" - -// Deeply nested -engine.execute( - '{{#if (and (or (lt age 18) (gt age 65)) (eq role "special"))}}discount{{else}}full price{{/if}}', - { age: 70, role: "special" }, -); -// → "discount" -``` - -### Static Analysis of Sub-Expressions - -Sub-expressions are **fully integrated** with the static analyzer. The key behaviors: - -**1. Argument validation** — every argument is resolved against the schema: - -```ts -// ❌ Unknown property in sub-expression argument -engine.analyze("{{#if (lt nonExistent 500)}}yes{{/if}}", schema); -// valid: false — UNKNOWN_PROPERTY - -// ❌ Missing nested property -engine.analyze("{{#if (lt account.foo 500)}}yes{{/if}}", schema); -// valid: false — UNKNOWN_PROPERTY - -// ❌ Too few arguments -engine.analyze("{{#if (lt age)}}yes{{/if}}", schema); -// valid: false — MISSING_ARGUMENT -``` - -**2. Type checking** — parameter types are validated against helper declarations: - -```ts -// ❌ String where number is expected -engine.analyze("{{#if (lt name 500)}}yes{{/if}}", schema); -// valid: false — TYPE_MISMATCH: "lt" parameter "a" expects number, got string -``` - -**3. Output type inference** — the output schema is based on the **branches**, not the condition: - -```ts -// The condition (lt ...) returns boolean, but the output type -// comes from the branch content: - -engine.analyze("{{#if (lt age 18)}}{{name}}{{else}}{{age}}{{/if}}", schema).outputSchema; -// → { oneOf: [{ type: "string" }, { type: "number" }] } -// (NOT boolean — the condition type doesn't leak into the output) - -engine.analyze("{{#if (gt score 50)}}{{age}}{{else}}{{score}}{{/if}}", schema).outputSchema; -// → { type: "number" } -// (both branches are number → simplified to single type) - -engine.analyze("{{#if (eq age 18)}}42{{else}}true{{/if}}", schema).outputSchema; -// → { oneOf: [{ type: "number" }, { type: "boolean" }] } - -// Chained else-if pattern -engine.analyze( - "{{#if (lt age 18)}}minor{{else}}{{#if (lt age 65)}}adult{{else}}senior{{/if}}{{/if}}", - schema, -).outputSchema; -// → { type: "string" } -// (all branches are string literals → simplified) -``` - -**4. Unknown helpers** — unregistered helpers emit a warning (not an error): - -```ts -engine.analyze("{{#if (myCustomCheck age)}}yes{{/if}}", schema); -// valid: true, but 1 warning: UNKNOWN_HELPER "myCustomCheck" -``` - ---- - -## Custom Helpers - -### `registerHelper` - -Register a custom helper with type metadata for static analysis: - -```ts -const engine = new Typebars(); - -engine.registerHelper("uppercase", { - fn: (value) => String(value).toUpperCase(), - params: [ - { name: "value", type: { type: "string" }, description: "The string to convert" }, - ], - returnType: { type: "string" }, - description: "Converts to UPPERCASE", -}); - -// Execution -engine.execute("{{uppercase name}}", { name: "alice" }); -// → "ALICE" - -// Static analysis uses the declared returnType -engine.analyze("{{uppercase name}}", { - type: "object", - properties: { name: { type: "string" } }, -}).outputSchema; -// → { type: "string" } -``` - -Helpers can also be passed at construction time: - -```ts -const engine = new Typebars({ - helpers: [ - { - name: "uppercase", - fn: (value) => String(value).toUpperCase(), - params: [{ name: "value", type: { type: "string" } }], - returnType: { type: "string" }, - }, - { - name: "double", - fn: (value) => Number(value) * 2, - params: [{ name: "value", type: { type: "number" } }], - returnType: { type: "number" }, - }, - ], -}); -``` - -`registerHelper` returns `this` for chaining: - -```ts -engine - .registerHelper("upper", { fn: (v) => String(v).toUpperCase(), returnType: { type: "string" } }) - .registerHelper("lower", { fn: (v) => String(v).toLowerCase(), returnType: { type: "string" } }); -``` - -### `defineHelper` (Type-Safe) - -`defineHelper()` infers the TypeScript types of your `fn` arguments from the JSON Schemas declared in `params`: - -```ts -import { Typebars, defineHelper } from "typebars"; - -const concatHelper = defineHelper({ - name: "concat", - description: "Concatenates two strings", - params: [ - { name: "a", type: { type: "string" }, description: "First string" }, - { name: "b", type: { type: "string" }, description: "Second string" }, - { name: "sep", type: { type: "string" }, description: "Separator", optional: true }, - ] as const, - fn: (a, b, sep) => { - // TypeScript infers: a: string, b: string, sep: string | undefined - return `${a}${sep ?? ""}${b}`; - }, - returnType: { type: "string" }, -}); - -const engine = new Typebars({ helpers: [concatHelper] }); -``` - ---- - -## Template Identifiers (`{{key:N}}`) - -The `{{key:N}}` syntax references variables from **different data sources**, identified by a numeric ID. Useful in workflow engines or multi-step pipelines. - -### Analysis with Identifier Schemas - -Each identifier maps to its own JSON Schema. Pass them via the `options` object: - -```ts -const engine = new Typebars(); - -const inputSchema = { type: "object", properties: {} }; - -const identifierSchemas = { - 1: { - type: "object", - properties: { meetingId: { type: "string" } }, - }, - 2: { - type: "object", - properties: { leadName: { type: "string" } }, - }, -}; - -// ✅ Valid — meetingId exists in identifier 1's schema -engine.analyze("{{meetingId:1}}", inputSchema, { identifierSchemas }); -// → valid: true, outputSchema: { type: "string" } - -// ❌ Invalid — identifier 1 doesn't have "badKey" -engine.analyze("{{badKey:1}}", inputSchema, { identifierSchemas }); -// → valid: false, code: IDENTIFIER_PROPERTY_NOT_FOUND - -// ❌ Invalid — identifier 99 doesn't exist -engine.analyze("{{meetingId:99}}", inputSchema, { identifierSchemas }); -// → valid: false, code: UNKNOWN_IDENTIFIER - -// ❌ Invalid — identifiers used but no schemas provided -engine.analyze("{{meetingId:1}}", inputSchema); -// → valid: false, code: MISSING_IDENTIFIER_SCHEMAS -``` - -### Mixing Identifier and Regular Expressions - -Regular expressions validate against `inputSchema`, identifier expressions against `identifierSchemas`: - -```ts -const schema = { - type: "object", - properties: { name: { type: "string" } }, -}; - -const idSchemas = { - 1: { - type: "object", - properties: { meetingId: { type: "string" } }, - }, -}; - -// ✅ "name" validated against schema, "meetingId:1" against idSchemas[1] -engine.analyze("{{name}} — {{meetingId:1}}", schema, { - identifierSchemas: idSchemas, -}); -// → valid: true -``` - -### Execution with Identifier Data - -```ts -const result = engine.execute( - "Meeting: {{meetingId:1}}, Lead: {{leadName:2}}", - {}, - { - identifierData: { - 1: { meetingId: "MTG-42" }, - 2: { leadName: "Alice" }, - }, - }, -); -// → "Meeting: MTG-42, Lead: Alice" - -// Single expression preserves type -engine.execute("{{count:1}}", {}, { - identifierData: { 1: { count: 42 } }, -}); -// → 42 (number) -``` - -### `analyzeAndExecute` with Identifiers - -```ts -const { analysis, value } = engine.analyzeAndExecute( - "{{total:1}}", - {}, - {}, - { - identifierSchemas: { - 1: { type: "object", properties: { total: { type: "number" } } }, - }, - identifierData: { - 1: { total: 99.95 }, - }, - }, -); - -analysis.valid; // true -analysis.outputSchema; // { type: "number" } -value; // 99.95 -``` - ---- - -## Output Type Coercion (`coerceSchema`) - -By default, static literal values in templates are auto-detected by `detectLiteralType`: -- `"123"` → `number` -- `"true"` → `boolean` -- `"null"` → `null` -- `"hello"` → `string` - -The `inputSchema` **never** influences this detection. However, you can provide an explicit `coerceSchema` in the options to override the output type inference for static literals. - -### Why `coerceSchema`? - -When building objects from templates, you may want to force the output type of a static value to match a specific schema — for example, keeping `"123"` as a `string` instead of auto-detecting it as `number`. The `coerceSchema` is a **separate source of truth** from `inputSchema`, which avoids false positives in validation. - -### Basic Usage - -```ts -const engine = new Typebars(); - -// Without coerceSchema — "123" is auto-detected as number -engine.analyze("123", { type: "string" }); -// → outputSchema: { type: "number" } - -// With coerceSchema — "123" respects the coercion schema -engine.analyze("123", { type: "string" }, { - coerceSchema: { type: "string" }, -}); -// → outputSchema: { type: "string" } -``` - -### Object Templates with `coerceSchema` - -For object templates, `coerceSchema` is resolved per-property and propagated recursively through nested objects: - -```ts -const inputSchema = { - type: "object", - properties: { - userName: { type: "string" }, - }, -}; - -const coerceSchema = { - type: "object", - properties: { - meetingId: { type: "string" }, - config: { - type: "object", - properties: { - retries: { type: "string" }, - }, - }, - }, -}; - -const result = engine.analyze( - { - meetingId: "12345", // coerceSchema says string → stays string - count: "42", // not in coerceSchema → detectLiteralType → number - label: "{{userName}}", // Handlebars expression → resolved from inputSchema - config: { - retries: "3", // coerceSchema says string → stays string - }, - }, - inputSchema, - { coerceSchema }, -); - -result.outputSchema; -// → { -// type: "object", -// properties: { -// meetingId: { type: "string" }, ← coerced -// count: { type: "number" }, ← auto-detected -// label: { type: "string" }, ← from inputSchema -// config: { -// type: "object", -// properties: { -// retries: { type: "string" }, ← coerced (deep propagation) -// }, -// required: ["retries"], -// }, -// }, -// required: ["meetingId", "count", "label", "config"], -// } -``` - -### Rules - -| Scenario | Output type | +| Document | Description | |----------|-------------| -| Static literal, no `coerceSchema` | `detectLiteralType` (e.g. `"123"` → `number`) | -| Static literal, `coerceSchema` with primitive type | Respects `coerceSchema` type | -| Static literal, `coerceSchema` with non-primitive type (object, array) | Falls back to `detectLiteralType` | -| Static literal, `coerceSchema` with no `type` | Falls back to `detectLiteralType` | -| Handlebars expression (`{{expr}}`) | Always resolved from `inputSchema` — `coerceSchema` ignored | -| Mixed template (`text + {{expr}}`) | Always `string` — `coerceSchema` ignored | -| JS primitive literal (`42`, `true`, `null`) | Always `inferPrimitiveSchema` — `coerceSchema` ignored | -| Property not in `coerceSchema` | Falls back to `detectLiteralType` | - -### With `analyzeAndExecute` - -`coerceSchema` also works with `analyzeAndExecute`: - -```ts -const { analysis, value } = engine.analyzeAndExecute( - { meetingId: "12345", name: "{{userName}}" }, - inputSchema, - { userName: "Alice" }, - { - coerceSchema: { - type: "object", - properties: { meetingId: { type: "string" } }, - }, - }, -); - -analysis.outputSchema; -// → { type: "object", properties: { meetingId: { type: "string" }, name: { type: "string" } }, ... } -value; -// → { meetingId: "12345", name: "Alice" } -``` - -### Standalone `analyze()` Function - -The standalone `analyze()` function from `src/analyzer.ts` also accepts `coerceSchema`: - -```ts -import { analyze } from "typebars/analyzer"; - -analyze("123", { type: "string" }, { coerceSchema: { type: "string" } }); -// → outputSchema: { type: "string" } -``` - ---- - -## Error Handling - -### `TemplateParseError` - -Thrown when the template has invalid Handlebars syntax: - -```ts -try { - engine.execute("{{#if}}unclosed", {}); -} catch (err) { - // err instanceof TemplateParseError - // err.message → "Parse error: ..." - // err.loc → { line, column } if available -} -``` - -### `TemplateAnalysisError` - -Thrown when `execute()` is called with a `schema` option and the template fails validation: - -```ts -try { - engine.execute("{{unknown}}", data, { - schema: { type: "object", properties: { name: { type: "string" } } }, - }); -} catch (err) { - // err instanceof TemplateAnalysisError - err.diagnostics; // TemplateDiagnostic[] - err.errors; // only severity: "error" - err.warnings; // only severity: "warning" - err.errorCount; // number - err.warningCount; // number - err.toJSON(); // serializable for API responses -} -``` - -The `toJSON()` method produces a clean structure for HTTP APIs: - -```ts -// Express / Hono / etc. -res.status(400).json(err.toJSON()); -// → { -// name: "TemplateAnalysisError", -// message: "Static analysis failed with 1 error(s): ...", -// errorCount: 1, -// warningCount: 0, -// diagnostics: [{ severity, code, message, loc, source, details }], -// } -``` - -### Syntax Validation (No Schema) - -For live editors, check syntax without a schema: - -```ts -engine.isValidSyntax("Hello {{name}}"); // true -engine.isValidSyntax("{{#if x}}yes{{/if}}"); // true -engine.isValidSyntax("{{#if x}}oops{{/unless}}"); // false -``` - ---- - -## Configuration & API Reference - -### Constructor - -```ts -const engine = new Typebars({ - astCacheSize: 256, // LRU cache for parsed ASTs (default: 256) - compilationCacheSize: 256, // LRU cache for Handlebars compilations (default: 256) - helpers: [], // Custom helpers to register at construction -}); -``` - -### `TemplateInput` - -All methods accept a `TemplateInput`: - -```ts -type TemplateInput = - | string // Handlebars template - | number // Literal passthrough - | boolean // Literal passthrough - | null // Literal passthrough - | TemplateInputObject // Object where each property is a TemplateInput -``` - -### Methods - -| Method | Description | -|--------|-------------| -| `analyze(template, inputSchema, options?)` | Validates template + infers output schema. Options: `{ identifierSchemas?, coerceSchema? }`. Returns `AnalysisResult` | -| `validate(template, inputSchema, options?)` | Like `analyze()` but without `outputSchema`. Returns `ValidationResult` | -| `execute(template, data, options?)` | Renders the template. Options: `{ schema?, identifierData?, identifierSchemas? }` | -| `analyzeAndExecute(template, inputSchema, data, options?)` | Analyze + execute in one call. Options: `{ identifierSchemas?, identifierData?, coerceSchema? }`. Returns `{ analysis, value }` | -| `compile(template)` | Returns a `CompiledTemplate` (parse-once, execute-many) | -| `isValidSyntax(template)` | Syntax check only (no schema needed). Returns `boolean` | -| `registerHelper(name, definition)` | Register a custom helper. Returns `this` | -| `unregisterHelper(name)` | Remove a helper. Returns `this` | -| `hasHelper(name)` | Check if a helper is registered | -| `clearCaches()` | Clear all internal caches | - -### `AnalyzeOptions` - -```ts -interface AnalyzeOptions { - identifierSchemas?: Record; // schemas by identifier - coerceSchema?: JSONSchema7; // output type coercion -} -``` - -### `AnalysisResult` - -```ts -interface AnalysisResult { - valid: boolean; // true if no errors - diagnostics: TemplateDiagnostic[]; // errors + warnings - outputSchema: JSONSchema7; // inferred output type -} -``` - -### `CompiledTemplate` - -Returned by `engine.compile()`. Has the same methods but without re-parsing: - -| Method | Description | -|--------|-------------| -| `execute(data, options?)` | Render with data | -| `analyze(inputSchema, identifierSchemas?)` | Validate + infer output schema | -| `validate(inputSchema, identifierSchemas?)` | Validate only | -| `analyzeAndExecute(inputSchema, data, options?)` | Both at once | +| [Getting Started](docs/getting-started.md) | Installation, quick start, and how the engine works | +| [Static Analysis](docs/static-analysis.md) | Input validation, output schema inference, and diagnostics | +| [Schema Features](docs/schema-features.md) | `$ref` resolution, combinators, `additionalProperties`, array `.length` | +| [Execution & Compiled Templates](docs/execution.md) | Type preservation, execution modes, and compile-once / execute-many | +| [Templates](docs/templates.md) | Object templates, array templates, and block helpers (`#if`, `#each`, `#with`) | +| [Built-in & Custom Helpers](docs/helpers.md) | Math, logical, comparison, `map` helper, and custom helper registration | +| [Template Identifiers](docs/identifiers.md) | The `{{key:N}}` syntax for multi-source data pipelines | +| [Advanced Features](docs/advanced.md) | `coerceSchema`, `excludeTemplateExpression`, and the `$root` token | +| [Error Handling](docs/error-handling.md) | Error hierarchy, diagnostics structure, and syntax validation | +| [API Reference](docs/api-reference.md) | Full API: constructor, methods, types, and options | + +--- + +## Key Features + +- **Static analysis** — validate templates against JSON Schema before execution ([docs](docs/static-analysis.md)) +- **Output schema inference** — know the exact type of the result without running anything ([docs](docs/static-analysis.md#output-schema-inference)) +- **Type preservation** — `{{age}}` returns `30` (number), not `"30"` ([docs](docs/execution.md)) +- **Object & array templates** — pass structured inputs, get structured outputs ([docs](docs/templates.md)) +- **Block helpers** — `#if`, `#unless`, `#each`, `#with` with full static analysis ([docs](docs/templates.md#block-helpers)) +- **Built-in helpers** — math, logical, comparison, and `map` — all statically analyzed ([docs](docs/helpers.md)) +- **Custom helpers** — register your own with type metadata for full analysis integration ([docs](docs/helpers.md#custom-helpers)) +- **Template identifiers** — `{{key:N}}` syntax for multi-source workflows ([docs](docs/identifiers.md)) +- **Output type coercion** — control how static literals are typed with `coerceSchema` ([docs](docs/advanced.md#output-type-coercion-coerceschema)) +- **Expression filtering** — exclude dynamic expressions from output with `excludeTemplateExpression` ([docs](docs/advanced.md#exclude-template-expressions)) +- **`$root` token** — reference the entire root context for primitive schemas ([docs](docs/advanced.md#root-token)) +- **Compiled templates** — parse once, execute many times ([docs](docs/execution.md#compiled-templates)) +- **JSON Schema v7** — `$ref`, `allOf`/`anyOf`/`oneOf`, `additionalProperties` ([docs](docs/schema-features.md)) --- diff --git a/docs/advanced.md b/docs/advanced.md new file mode 100644 index 0000000..00ab772 --- /dev/null +++ b/docs/advanced.md @@ -0,0 +1,458 @@ +# Advanced Features + +> **[← Back to README](../README.md)** | **Related:** [Static Analysis](static-analysis.md) · [Execution](execution.md) · [Templates](templates.md) · [API Reference](api-reference.md) + +This page covers advanced options that give you fine-grained control over output type inference, expression filtering, and root context access. + +--- + +## Table of Contents + +- [Output Type Coercion (`coerceSchema`)](#output-type-coercion-coerceschema) + - [Why `coerceSchema`?](#why-coerceschema) + - [Basic Usage](#basic-usage) + - [Object Templates with `coerceSchema`](#object-templates-with-coerceschema) + - [Array Templates with `coerceSchema`](#array-templates-with-coerceschema) + - [Rules](#rules) + - [With `analyzeAndExecute`](#with-analyzeandexecute) +- [Exclude Template Expressions](#exclude-template-expressions) + - [Why `excludeTemplateExpression`?](#why-excludetemplateexpression) + - [Object Templates](#object-templates) + - [Array Templates](#array-templates) + - [Root-Level Strings](#root-level-strings) + - [Combined with `coerceSchema`](#combined-with-coerceschema) +- [`$root` Token](#root-token) + - [Primitive Schemas](#primitive-schemas) + - [Object Schemas](#object-schemas) + - [Path Traversal is Forbidden](#path-traversal-is-forbidden) + - [`$root` Inside Block Helpers](#root-inside-block-helpers) + - [`$root` with Identifiers](#root-with-identifiers) + +--- + +## Output Type Coercion (`coerceSchema`) + +### Why `coerceSchema`? + +By default, static literal values in templates are auto-detected by `detectLiteralType`: +- `"123"` → `number` +- `"true"` → `boolean` +- `"null"` → `null` +- `"hello"` → `string` + +The `inputSchema` **never** influences this detection — it only describes available variables for [input validation](static-analysis.md#input-validation). + +When building [object templates](templates.md#object-templates), you may want to force the output type of a static value to match a specific schema — for example, keeping `"123"` as a `string` instead of auto-detecting it as `number`. The `coerceSchema` is a **separate source of truth** from `inputSchema`, which avoids false positives in validation. + +### Basic Usage + +Pass `coerceSchema` in the options to `analyze()`, `analyzeAndExecute()`, or on a [compiled template](execution.md#compiled-templates): + +```ts +const engine = new Typebars(); + +// Without coerceSchema — "123" is auto-detected as number +engine.analyze("123", { type: "string" }); +// → outputSchema: { type: "number" } + +// With coerceSchema — "123" respects the coercion schema +engine.analyze("123", { type: "string" }, { + coerceSchema: { type: "string" }, +}); +// → outputSchema: { type: "string" } +``` + +`coerceSchema` also affects **execution** — a string that would normally be coerced to a number stays as a string: + +```ts +engine.execute("123", {}); +// → 123 (number — auto-detected) + +engine.execute("123", {}, { coerceSchema: { type: "string" } }); +// → "123" (string — coerced) +``` + +### Object Templates with `coerceSchema` + +For object templates, `coerceSchema` is resolved **per-property** and propagated recursively through nested objects. The `coerceSchema` must be an object schema with `properties` matching the template keys: + +```ts +const inputSchema = { + type: "object", + properties: { + userName: { type: "string" }, + }, +}; + +const coerceSchema = { + type: "object", + properties: { + meetingId: { type: "string" }, + config: { + type: "object", + properties: { + retries: { type: "string" }, + }, + }, + }, +}; + +const result = engine.analyze( + { + meetingId: "12345", // coerceSchema says string → stays string + count: "42", // not in coerceSchema → detectLiteralType → number + label: "{{userName}}", // Handlebars expression → resolved from inputSchema + config: { + retries: "3", // coerceSchema says string → stays string + }, + }, + inputSchema, + { coerceSchema }, +); + +result.outputSchema; +// → { +// type: "object", +// properties: { +// meetingId: { type: "string" }, ← coerced +// count: { type: "number" }, ← auto-detected +// label: { type: "string" }, ← from inputSchema +// config: { +// type: "object", +// properties: { +// retries: { type: "string" }, ← coerced (deep propagation) +// }, +// required: ["retries"], +// }, +// }, +// required: ["meetingId", "count", "label", "config"], +// } +``` + +### Array Templates with `coerceSchema` + +For [array templates](templates.md#array-templates), `coerceSchema` with an `items` property is propagated to each element: + +```ts +const coerceSchema = { + type: "array", + items: { type: "string" }, +}; + +engine.analyze( + ["123", "456", "hello"], + {}, + { coerceSchema }, +).outputSchema; +// → items coerced as strings instead of auto-detecting "123" and "456" as numbers +``` + +### Rules + +| Scenario | Output type | +|----------|-------------| +| Static literal, no `coerceSchema` | `detectLiteralType` (e.g. `"123"` → `number`) | +| Static literal, `coerceSchema` with primitive type | Respects `coerceSchema` type | +| Static literal, `coerceSchema` with non-primitive type (object, array) | Falls back to `detectLiteralType` | +| Static literal, `coerceSchema` with no `type` | Falls back to `detectLiteralType` | +| Handlebars expression (`{{expr}}`) | Always resolved from `inputSchema` — `coerceSchema` ignored | +| Mixed template (`text + {{expr}}`) | Always `string` — `coerceSchema` ignored | +| JS primitive literal (`42`, `true`, `null`) | Always `inferPrimitiveSchema` — `coerceSchema` ignored | +| Property not in `coerceSchema` | Falls back to `detectLiteralType` | + +> **Key principle:** `coerceSchema` only affects **static string literals** (strings without `{{…}}`). Handlebars expressions, mixed templates, and JS primitive literals are never affected. + +### With `analyzeAndExecute` + +`coerceSchema` works with `analyzeAndExecute` — it affects both the analysis output schema and the execution coercion: + +```ts +const { analysis, value } = engine.analyzeAndExecute( + { meetingId: "12345", name: "{{userName}}" }, + inputSchema, + { userName: "Alice" }, + { + coerceSchema: { + type: "object", + properties: { meetingId: { type: "string" } }, + }, + }, +); + +analysis.outputSchema; +// → { type: "object", properties: { meetingId: { type: "string" }, name: { type: "string" } }, ... } +value; +// → { meetingId: "12345", name: "Alice" } +// (meetingId stays as string "12345" instead of being coerced to number 12345) +``` + +--- + +## Exclude Template Expressions + +### Why `excludeTemplateExpression`? + +The `excludeTemplateExpression` option filters out properties (or array elements) whose values contain Handlebars expressions (`{{…}}`). Only static values — literals, plain strings without expressions — are retained in the output. + +This is useful when you want the output schema to describe only the **known, compile-time-constant** portion of the template, or when you want to separate static configuration from dynamic content. + +### Object Templates + +When `excludeTemplateExpression: true` is set, object properties containing Handlebars expressions are **removed** from the output schema and from the executed result: + +```ts +const engine = new Typebars(); + +const inputSchema = { + type: "object", + properties: { name: { type: "string" } }, +}; + +// Analysis — dynamic properties are excluded from the output schema +const result = engine.analyze( + { + greeting: "Hello {{name}}!", // contains expression → excluded + version: "42", // plain string → kept + active: true, // literal → kept + }, + inputSchema, + { excludeTemplateExpression: true }, +); + +result.outputSchema; +// → { +// type: "object", +// properties: { +// version: { type: "number" }, ← kept (static literal, auto-detected) +// active: { type: "boolean" }, ← kept (literal passthrough) +// }, +// required: ["version", "active"], +// } +// "greeting" is excluded because it contains {{name}} + +// Execution — dynamic properties are excluded from the result +engine.execute( + { + greeting: "Hello {{name}}!", + version: "42", + active: true, + }, + { name: "Alice" }, + { excludeTemplateExpression: true }, +); +// → { version: 42, active: true } +// "greeting" is excluded from the output +``` + +The filtering is recursive — nested objects are also filtered: + +```ts +engine.execute( + { + config: { + label: "{{name}}", // excluded + retries: "3", // kept + }, + status: "active", // kept + }, + { name: "Alice" }, + { excludeTemplateExpression: true }, +); +// → { config: { retries: 3 }, status: "active" } +``` + +### Array Templates + +For [array templates](templates.md#array-templates), elements containing expressions are filtered out: + +```ts +engine.execute( + ["Hello {{name}}!", "static value", 42, "{{age}}"], + { name: "Alice", age: 30 }, + { excludeTemplateExpression: true }, +); +// → ["static value", 42] +// "Hello {{name}}!" and "{{age}}" are excluded +``` + +### Root-Level Strings + +When `excludeTemplateExpression` is used on a **root-level string** (not inside an object or array), there is no parent to remove the entry from. In this case: + +- **Analysis**: the template is analyzed normally (no filtering possible at root) +- **Execution**: returns `null` if the string contains expressions + +```ts +engine.execute("Hello {{name}}!", { name: "Alice" }, { + excludeTemplateExpression: true, +}); +// → null (root-level string with expression) + +engine.execute("static text", {}, { + excludeTemplateExpression: true, +}); +// → "static text" (no expression → kept) +``` + +### Combined with `coerceSchema` + +`excludeTemplateExpression` and `coerceSchema` can be used together. The filtering happens first, then coercion applies to the remaining static values: + +```ts +engine.analyze( + { + meetingId: "12345", + greeting: "Hello {{name}}!", + }, + inputSchema, + { + excludeTemplateExpression: true, + coerceSchema: { + type: "object", + properties: { meetingId: { type: "string" } }, + }, + }, +).outputSchema; +// → { +// type: "object", +// properties: { +// meetingId: { type: "string" }, ← kept + coerced +// }, +// required: ["meetingId"], +// } +// "greeting" excluded, "meetingId" coerced to string +``` + +--- + +## `$root` Token + +The `$root` token allows referencing the **entire input schema / data context** directly. This is primarily useful when the `inputSchema` is a **primitive type** (e.g. `{ type: "string" }`) rather than an object with properties. + +### Primitive Schemas + +When the input schema is a primitive type, there are no named properties to reference. Use `{{ $root }}` to access the entire value: + +```ts +const engine = new Typebars(); + +// String schema +engine.analyze("{{ $root }}", { type: "string" }); +// → valid: true, outputSchema: { type: "string" } + +engine.execute("{{ $root }}", "hello"); +// → "hello" + +// Number schema +engine.analyze("{{ $root }}", { type: "number" }); +// → valid: true, outputSchema: { type: "number" } + +engine.execute("{{ $root }}", 42); +// → 42 + +// Boolean schema +engine.analyze("{{ $root }}", { type: "boolean" }); +// → valid: true, outputSchema: { type: "boolean" } + +engine.execute("{{ $root }}", true); +// → true +``` + +### Object Schemas + +`$root` also works with object schemas — it resolves to the **entire object**: + +```ts +const schema = { + type: "object", + properties: { + name: { type: "string" }, + age: { type: "number" }, + }, +}; + +engine.analyze("{{ $root }}", schema); +// → valid: true, outputSchema: the full object schema + +engine.execute("{{ $root }}", { name: "Alice", age: 30 }); +// → { name: "Alice", age: 30 } +``` + +### Path Traversal is Forbidden + +Using `$root` with dot notation (e.g. `{{ $root.name }}`) is **forbidden** and produces a `ROOT_PATH_TRAVERSAL` diagnostic error. This is because properties are already directly accessible in the context — use `{{ name }}` instead of `{{ $root.name }}`. + +```ts +// ❌ Path traversal on $root → error +engine.analyze("{{ $root.name }}", schema); +// → valid: false, code: ROOT_PATH_TRAVERSAL + +engine.analyze("{{ $root.address.city }}", schema); +// → valid: false, code: ROOT_PATH_TRAVERSAL + +// ✅ Use the property directly instead +engine.analyze("{{ name }}", schema); +// → valid: true +``` + +The `ROOT_PATH_TRAVERSAL` check happens **before** property resolution — even if the property exists, the path traversal is rejected: + +```ts +engine.analyze("{{ $root.nonexistent }}", schema); +// → code: ROOT_PATH_TRAVERSAL (NOT UNKNOWN_PROPERTY) +``` + +This applies everywhere — root-level templates, [object templates](templates.md#object-templates), mixed templates, and inside [block helpers](templates.md#block-helpers): + +```ts +// Object template +engine.analyze({ displayName: "{{ $root.name }}" }, schema); +// → ROOT_PATH_TRAVERSAL + +// Mixed template +engine.analyze("Hello {{ $root.name }}!", schema); +// → ROOT_PATH_TRAVERSAL +``` + +### `$root` Inside Block Helpers + +`$root` (without path traversal) can be used as a block helper condition: + +```ts +// ✅ $root as #if condition — checks truthiness of the entire root value +engine.analyze("{{#if $root}}yes{{/if}}", { type: "boolean" }); +// → valid: true + +// ❌ $root.active as #if condition → ROOT_PATH_TRAVERSAL +engine.analyze("{{#if $root.active}}active{{else}}inactive{{/if}}", schema); +// → valid: false, code: ROOT_PATH_TRAVERSAL +``` + +### `$root` with Identifiers + +`$root` can be combined with [template identifiers](identifiers.md). The `$root` resolves against the identifier's schema: + +```ts +const identifierSchemas = { + 1: { type: "string" }, +}; + +// ✅ $root:1 → resolves to the entire identifier 1 schema +engine.analyze("{{ $root:1 }}", {}, { identifierSchemas }); +// → valid: true, outputSchema: { type: "string" } + +// ❌ $root.name:2 → ROOT_PATH_TRAVERSAL (path traversal still forbidden) +engine.analyze("{{ $root.name:2 }}", {}, { + identifierSchemas: { 2: schema }, +}); +// → valid: false, code: ROOT_PATH_TRAVERSAL +``` + +--- + +## What's Next? + +- **[Error Handling](error-handling.md)** — error hierarchy, diagnostics, and the `ROOT_PATH_TRAVERSAL` code +- **[Static Analysis](static-analysis.md)** — full diagnostics reference and output schema inference +- **[Templates](templates.md)** — object templates, array templates, and block helpers +- **[API Reference](api-reference.md)** — full options signatures for `AnalyzeOptions`, `ExecuteOptions`, etc. \ No newline at end of file diff --git a/docs/api-reference.md b/docs/api-reference.md new file mode 100644 index 0000000..60f174e --- /dev/null +++ b/docs/api-reference.md @@ -0,0 +1,715 @@ +# API Reference + +> **[← Back to README](../README.md)** | **Related:** [Getting Started](getting-started.md) · [Static Analysis](static-analysis.md) · [Execution](execution.md) · [Error Handling](error-handling.md) + +Complete reference for the Typebars public API — classes, methods, types, and options. + +--- + +## Table of Contents + +- [`Typebars` Class](#typebars-class) + - [Constructor](#constructor) + - [`analyze()`](#analyze) + - [`validate()`](#validate) + - [`execute()`](#execute) + - [`analyzeAndExecute()`](#analyzeandexecute) + - [`compile()`](#compile) + - [`isValidSyntax()`](#isvalidsyntax) + - [`registerHelper()`](#registerhelper) + - [`unregisterHelper()`](#unregisterhelper) + - [`hasHelper()`](#hashelper) + - [`clearCaches()`](#clearcaches) +- [`CompiledTemplate` Class](#compiledtemplate-class) + - [`execute()`](#compiledtemplate-execute) + - [`analyze()`](#compiledtemplate-analyze) + - [`validate()`](#compiledtemplate-validate) + - [`analyzeAndExecute()`](#compiledtemplate-analyzeandexecute) +- [Types](#types) + - [`TemplateInput`](#templateinput) + - [`TemplateData`](#templatedata) + - [`TemplateInputObject`](#templateinputobject) + - [`TemplateInputArray`](#templateinputarray) + - [`AnalysisResult`](#analysisresult) + - [`ValidationResult`](#validationresult) + - [`TemplateDiagnostic`](#templatediagnostic) + - [`DiagnosticCode`](#diagnosticcode) + - [`DiagnosticDetails`](#diagnosticdetails) +- [Options](#options) + - [`TemplateEngineOptions`](#templateengineoptions) + - [`AnalyzeOptions`](#analyzeoptions) + - [`ExecuteOptions`](#executeoptions) + - [`AnalyzeAndExecuteOptions`](#analyzeandexecuteoptions) +- [Helper Types](#helper-types) + - [`HelperDefinition`](#helperdefinition) + - [`HelperConfig`](#helperconfig) + - [`HelperParam`](#helperparam) + - [`defineHelper()`](#definehelper) +- [Error Classes](#error-classes) +- [Type Guards](#type-guards) +- [Exports](#exports) + +--- + +## `Typebars` Class + +The main engine class. Each instance has its own isolated Handlebars environment, helper registry, and LRU caches. + +```ts +import { Typebars } from "typebars"; +``` + +### Constructor + +```ts +new Typebars(options?: TemplateEngineOptions) +``` + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `options.astCacheSize` | `number` | `256` | LRU cache size for parsed ASTs | +| `options.compilationCacheSize` | `number` | `256` | LRU cache size for compiled Handlebars templates | +| `options.helpers` | `HelperConfig[]` | `[]` | Custom helpers to register at construction time | + +```ts +const engine = new Typebars({ + astCacheSize: 512, + compilationCacheSize: 512, + helpers: [ + { + name: "uppercase", + fn: (value) => String(value).toUpperCase(), + params: [{ name: "value", type: { type: "string" } }], + returnType: { type: "string" }, + }, + ], +}); +``` + +Built-in helpers ([math](helpers.md#math-helpers), [logical](helpers.md#logical--comparison-helpers), [map](helpers.md#map-helper)) are automatically registered before custom helpers. + +--- + +### `analyze()` + +Statically validates a template against an input schema and infers the output schema. + +```ts +analyze( + template: TemplateInput, + inputSchema?: JSONSchema7, + options?: AnalyzeOptions, +): AnalysisResult +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `template` | [`TemplateInput`](#templateinput) | The template to analyze | +| `inputSchema` | `JSONSchema7` | JSON Schema describing available variables (default: `{}`) | +| `options` | [`AnalyzeOptions`](#analyzeoptions) | Optional — identifier schemas, coercion schema, expression filtering | + +**Returns:** [`AnalysisResult`](#analysisresult) — `{ valid, diagnostics, outputSchema }` + +**Throws:** [`TemplateParseError`](error-handling.md#templateparseerror) on invalid syntax, [`UnsupportedSchemaError`](error-handling.md#unsupportedschemaerror) on `if`/`then`/`else` schemas. + +**Does not throw** on validation failures — check `result.valid` and `result.diagnostics` instead. + +```ts +const result = engine.analyze("{{name}}", schema); +if (result.valid) { + console.log(result.outputSchema); // { type: "string" } +} else { + console.log(result.diagnostics); // TemplateDiagnostic[] +} +``` + +See [Static Analysis](static-analysis.md) for detailed behavior. + +--- + +### `validate()` + +Like `analyze()` but without computing the `outputSchema`. Slightly lighter — useful when you only need validation. + +```ts +validate( + template: TemplateInput, + inputSchema?: JSONSchema7, + options?: AnalyzeOptions, +): ValidationResult +``` + +**Returns:** [`ValidationResult`](#validationresult) — `{ valid, diagnostics }` (no `outputSchema`). + +```ts +const result = engine.validate("{{name}}", schema); +result.valid; // boolean +result.diagnostics; // TemplateDiagnostic[] +``` + +--- + +### `execute()` + +Renders a template with data. Optionally validates against a schema first. + +```ts +execute( + template: TemplateInput, + data: TemplateData, + options?: ExecuteOptions, +): unknown +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `template` | [`TemplateInput`](#templateinput) | The template to execute | +| `data` | [`TemplateData`](#templatedata) | The data context for rendering | +| `options` | [`ExecuteOptions`](#executeoptions) | Optional — schema for pre-execution validation, identifier data, coercion, expression filtering | + +**Returns:** The rendered value. The type depends on the template structure — see [Type Preservation](execution.md#type-preservation). + +**Throws:** +- [`TemplateParseError`](error-handling.md#templateparseerror) on invalid syntax +- [`TemplateAnalysisError`](error-handling.md#templateanalysiserror) if `options.schema` is provided and analysis fails +- [`TemplateRuntimeError`](error-handling.md#templateruntimeerror) on Handlebars runtime errors + +```ts +engine.execute("{{age}}", { age: 30 }); // → 30 (number) +engine.execute("Hello {{name}}", { name: "A" }); // → "Hello A" (string) +engine.execute(42, {}); // → 42 (literal passthrough) +``` + +--- + +### `analyzeAndExecute()` + +Performs both static analysis and execution in a single call. If analysis fails, execution is skipped and `value` is `undefined`. + +```ts +analyzeAndExecute( + template: TemplateInput, + inputSchema: JSONSchema7, + data: TemplateData, + options?: AnalyzeAndExecuteOptions, +): { analysis: AnalysisResult; value: unknown } +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `template` | [`TemplateInput`](#templateinput) | The template to process | +| `inputSchema` | `JSONSchema7` | JSON Schema describing available variables | +| `data` | [`TemplateData`](#templatedata) | The data context for rendering | +| `options` | [`AnalyzeAndExecuteOptions`](#analyzeandexecuteoptions) | Optional — identifiers, coercion, expression filtering | + +**Returns:** `{ analysis: AnalysisResult, value: unknown }` — `value` is `undefined` if `analysis.valid` is `false`. + +```ts +const { analysis, value } = engine.analyzeAndExecute("{{age}}", schema, data); +analysis.outputSchema; // { type: "number" } +value; // 30 +``` + +--- + +### `compile()` + +Parses a template once and returns a reusable [`CompiledTemplate`](#compiledtemplate-class). Avoids re-parsing on repeated executions. + +```ts +compile(template: TemplateInput): CompiledTemplate +``` + +**Returns:** [`CompiledTemplate`](#compiledtemplate-class) + +**Throws:** [`TemplateParseError`](error-handling.md#templateparseerror) on invalid syntax. + +```ts +const tpl = engine.compile("Hello {{name}}!"); +tpl.execute({ name: "Alice" }); // → "Hello Alice!" +tpl.execute({ name: "Bob" }); // → "Hello Bob!" +``` + +See [Compiled Templates](execution.md#compiled-templates) for detailed usage. + +--- + +### `isValidSyntax()` + +Checks if a template string has valid Handlebars syntax. Does **not** validate against a schema. + +```ts +isValidSyntax(template: string): boolean +``` + +```ts +engine.isValidSyntax("Hello {{name}}"); // true +engine.isValidSyntax("{{#if x}}oops{{/unless}}"); // false +``` + +See [Syntax Validation](error-handling.md#syntax-validation). + +--- + +### `registerHelper()` + +Registers a custom helper with type metadata for static analysis. + +```ts +registerHelper(name: string, definition: HelperDefinition): this +``` + +Returns `this` for chaining. + +```ts +engine + .registerHelper("upper", { + fn: (v) => String(v).toUpperCase(), + returnType: { type: "string" }, + }) + .registerHelper("lower", { + fn: (v) => String(v).toLowerCase(), + returnType: { type: "string" }, + }); +``` + +See [Custom Helpers](helpers.md#custom-helpers) for detailed examples. + +--- + +### `unregisterHelper()` + +Removes a helper (including built-in ones). Invalidates the compilation cache. + +```ts +unregisterHelper(name: string): this +``` + +Returns `this` for chaining. + +--- + +### `hasHelper()` + +Checks whether a helper is registered on this instance. + +```ts +hasHelper(name: string): boolean +``` + +```ts +engine.hasHelper("add"); // true (built-in) +engine.hasHelper("custom"); // false +``` + +--- + +### `clearCaches()` + +Clears all internal caches (AST + compilation). Useful after configuration changes or to free memory. + +```ts +clearCaches(): void +``` + +--- + +## `CompiledTemplate` Class + +Returned by [`engine.compile()`](#compile). Provides the same operations as the engine but without re-parsing. + +Uses a discriminated union internally (`TemplateState`) with kinds: `"template"`, `"literal"`, `"object"`, and `"array"`. + +### `execute()` {#compiledtemplate-execute} + +```ts +execute(data: TemplateData, options?: ExecuteOptions): unknown +``` + +### `analyze()` {#compiledtemplate-analyze} + +```ts +analyze(inputSchema: JSONSchema7, options?: AnalyzeOptions): AnalysisResult +``` + +### `validate()` {#compiledtemplate-validate} + +```ts +validate(inputSchema: JSONSchema7, options?: AnalyzeOptions): ValidationResult +``` + +### `analyzeAndExecute()` {#compiledtemplate-analyzeandexecute} + +```ts +analyzeAndExecute( + inputSchema: JSONSchema7, + data: TemplateData, + options?: AnalyzeAndExecuteOptions, +): { analysis: AnalysisResult; value: unknown } +``` + +> **Note:** The parameter order for `CompiledTemplate` methods differs from `Typebars` methods — there is no `template` parameter since the template is already compiled. + +--- + +## Types + +### `TemplateInput` + +The input type accepted by the template engine. A recursive union: + +```ts +type TemplateInput = + | string // Handlebars template (parsed and executed) + | number // Literal passthrough + | boolean // Literal passthrough + | null // Literal passthrough + | TemplateInputArray // Array where each element is a TemplateInput + | TemplateInputObject // Object where each property is a TemplateInput +``` + +See [Templates](templates.md) for object and array template behavior. + +### `TemplateData` + +The data context accepted by `execute()` and `analyzeAndExecute()`: + +```ts +type TemplateData = + | string + | number + | boolean + | null + | undefined + | Record +``` + +### `TemplateInputObject` + +```ts +interface TemplateInputObject { + [key: string]: TemplateInput; +} +``` + +### `TemplateInputArray` + +```ts +type TemplateInputArray = TemplateInput[]; +``` + +### `AnalysisResult` + +Returned by `analyze()` and `analyzeAndExecute()`: + +```ts +interface AnalysisResult { + valid: boolean; // true if no error-severity diagnostics + diagnostics: TemplateDiagnostic[]; // all diagnostics (errors + warnings) + outputSchema: JSONSchema7; // inferred output type +} +``` + +### `ValidationResult` + +Returned by `validate()`: + +```ts +interface ValidationResult { + valid: boolean; + diagnostics: TemplateDiagnostic[]; +} +``` + +### `TemplateDiagnostic` + +A structured diagnostic object. See [Diagnostics](error-handling.md#diagnostics) for full details. + +```ts +interface TemplateDiagnostic { + severity: "error" | "warning"; + code: DiagnosticCode; + message: string; + loc?: { + start: { line: number; column: number }; + end: { line: number; column: number }; + }; + source?: string; + details?: DiagnosticDetails; +} +``` + +### `DiagnosticCode` + +A union type of all possible diagnostic codes: + +```ts +type DiagnosticCode = + | "UNKNOWN_PROPERTY" + | "TYPE_MISMATCH" + | "MISSING_ARGUMENT" + | "UNKNOWN_HELPER" + | "UNANALYZABLE" + | "MISSING_IDENTIFIER_SCHEMAS" + | "UNKNOWN_IDENTIFIER" + | "IDENTIFIER_PROPERTY_NOT_FOUND" + | "PARSE_ERROR" + | "ROOT_PATH_TRAVERSAL"; +``` + +See [Diagnostic Codes](error-handling.md#diagnostic-codes) for descriptions of each code. + +### `DiagnosticDetails` + +Optional structured context attached to diagnostics: + +```ts +interface DiagnosticDetails { + path?: string; + helperName?: string; + expected?: string; + actual?: string; + availableProperties?: string[]; + identifier?: number; +} +``` + +--- + +## Options + +### `TemplateEngineOptions` + +Passed to the [`Typebars` constructor](#constructor): + +```ts +interface TemplateEngineOptions { + astCacheSize?: number; // LRU cache for parsed ASTs (default: 256) + compilationCacheSize?: number; // LRU cache for Handlebars compilations (default: 256) + helpers?: HelperConfig[]; // Custom helpers to register at construction +} +``` + +### `AnalyzeOptions` + +Passed to `analyze()`, `validate()`, and the analysis portion of `analyzeAndExecute()`: + +```ts +interface AnalyzeOptions { + identifierSchemas?: Record; + coerceSchema?: JSONSchema7; + excludeTemplateExpression?: boolean; +} +``` + +| Field | Description | Docs | +|-------|-------------|------| +| `identifierSchemas` | Schemas by identifier number for the `{{key:N}}` syntax | [Identifiers](identifiers.md) | +| `coerceSchema` | Explicit coercion schema overriding auto-detection for static literals | [coerceSchema](advanced.md#output-type-coercion-coerceschema) | +| `excludeTemplateExpression` | When `true`, exclude entries containing `{{…}}` from the output | [excludeTemplateExpression](advanced.md#exclude-template-expressions) | + +### `ExecuteOptions` + +Passed to `execute()`: + +```ts +interface ExecuteOptions { + schema?: JSONSchema7; + identifierSchemas?: Record; + identifierData?: Record>; + coerceSchema?: JSONSchema7; + excludeTemplateExpression?: boolean; +} +``` + +| Field | Description | Docs | +|-------|-------------|------| +| `schema` | When provided, runs `analyze()` before execution and throws [`TemplateAnalysisError`](error-handling.md#templateanalysiserror) on failure | [Error Handling](error-handling.md#error-vs-diagnostic) | +| `identifierSchemas` | Schemas by identifier (for pre-execution analysis) | [Identifiers](identifiers.md) | +| `identifierData` | Data by identifier number | [Identifiers](identifiers.md#execution-with-identifier-data) | +| `coerceSchema` | Output type coercion for static literals | [coerceSchema](advanced.md#output-type-coercion-coerceschema) | +| `excludeTemplateExpression` | Exclude entries with Handlebars expressions | [excludeTemplateExpression](advanced.md#exclude-template-expressions) | + +### `AnalyzeAndExecuteOptions` + +Passed to `analyzeAndExecute()`: + +```ts +interface AnalyzeAndExecuteOptions { + identifierSchemas?: Record; + identifierData?: Record>; + coerceSchema?: JSONSchema7; + excludeTemplateExpression?: boolean; +} +``` + +Combines the analysis and execution options (except `schema`, which is implicit). + +--- + +## Helper Types + +### `HelperDefinition` + +The definition object passed to [`registerHelper()`](#registerhelper): + +```ts +interface HelperDefinition { + fn: (...args: unknown[]) => unknown; + params?: HelperParam[]; + returnType?: JSONSchema7; + description?: string; +} +``` + +| Field | Required | Description | +|-------|----------|-------------| +| `fn` | ✅ | The helper implementation function | +| `params` | ❌ | Parameter definitions for static analysis | +| `returnType` | ❌ | JSON Schema of the return value (used for output type inference) | +| `description` | ❌ | Human-readable description | + +### `HelperConfig` + +Used in `TemplateEngineOptions.helpers` — a `HelperDefinition` with a required `name`: + +```ts +interface HelperConfig extends HelperDefinition { + name: string; +} +``` + +### `HelperParam` + +Describes a single helper parameter: + +```ts +interface HelperParam { + name: string; + type?: JSONSchema7; + description?: string; + optional?: boolean; +} +``` + +| Field | Description | +|-------|-------------| +| `name` | Parameter name (used in diagnostic messages) | +| `type` | JSON Schema the argument must conform to (for type checking) | +| `description` | Human-readable description | +| `optional` | When `true`, the argument is not required | + +### `defineHelper()` + +A type-safe factory function that infers TypeScript types for the `fn` arguments from the `params` JSON Schemas: + +```ts +import { defineHelper } from "typebars"; + +const helper = defineHelper({ + name: "concat", + params: [ + { name: "a", type: { type: "string" } }, + { name: "b", type: { type: "string" } }, + ] as const, // ← `as const` is required for type inference + fn: (a, b) => `${a}${b}`, // TypeScript infers: a: string, b: string + returnType: { type: "string" }, +}); +``` + +**Signature:** + +```ts +function defineHelper

( + config: TypedHelperConfig

, +): HelperConfig +``` + +See [Custom Helpers — `defineHelper`](helpers.md#definehelper-type-safe) for detailed examples. + +--- + +## Error Classes + +All error classes are exported from `typebars`. See [Error Handling](error-handling.md) for detailed descriptions. + +```ts +import { + TemplateError, + TemplateParseError, + TemplateAnalysisError, + TemplateRuntimeError, + UnsupportedSchemaError, +} from "typebars"; +``` + +| Class | Thrown When | Key Properties | +|-------|------------|----------------| +| `TemplateError` | Base class — not thrown directly | `message` | +| `TemplateParseError` | Invalid Handlebars syntax | `message`, `loc?` | +| `TemplateAnalysisError` | `execute()` with `schema` option fails validation | `diagnostics`, `errors`, `warnings`, `errorCount`, `warningCount`, `toJSON()` | +| `TemplateRuntimeError` | Handlebars runtime failure | `message` | +| `UnsupportedSchemaError` | Schema uses `if`/`then`/`else` | `message` | + +--- + +## Type Guards + +Exported utility functions for narrowing `TemplateInput` values: + +```ts +import { isArrayInput } from "typebars"; +``` + +| Function | Description | +|----------|-------------| +| `isArrayInput(value)` | Returns `true` if the value is a `TemplateInputArray` | + +> **Important:** Always check `isArrayInput()` **before** checking for objects, because arrays are also `typeof "object"` in JavaScript. + +The following type guards are available from the source module but not re-exported from the package entry point: + +| Function | Description | +|----------|-------------| +| `isLiteralInput(value)` | Returns `true` if the value is `number`, `boolean`, or `null` | +| `isObjectInput(value)` | Returns `true` if the value is a `TemplateInputObject` (non-array object) | + +--- + +## Exports + +Everything exported from the `typebars` package entry point: + +```ts +// Classes +export { Typebars } from "./typebars"; + +// Types +export type { AnalyzeOptions } from "./analyzer"; +export type { + TemplateData, + TemplateInput, + TemplateInputArray, +} from "./types"; + +// Functions +export { defineHelper, isArrayInput } from "./types"; + +// Errors +export { + TemplateError, + TemplateParseError, + TemplateAnalysisError, + TemplateRuntimeError, + UnsupportedSchemaError, +} from "./errors"; +``` + +--- + +## What's Next? + +- **[Getting Started](getting-started.md)** — installation and quick start +- **[Static Analysis](static-analysis.md)** — detailed analysis behavior +- **[Execution](execution.md)** — type preservation and compiled templates +- **[Error Handling](error-handling.md)** — error hierarchy and diagnostics \ No newline at end of file diff --git a/docs/error-handling.md b/docs/error-handling.md new file mode 100644 index 0000000..4cae831 --- /dev/null +++ b/docs/error-handling.md @@ -0,0 +1,294 @@ +# Error Handling + +> **[← Back to README](../README.md)** | **Related:** [Static Analysis](static-analysis.md) · [Execution](execution.md) · [API Reference](api-reference.md) + +Typebars uses a structured error hierarchy for different failure modes. All error classes extend the base `TemplateError` class and provide rich context for debugging and API responses. + +--- + +## Table of Contents + +- [Error Hierarchy](#error-hierarchy) +- [`TemplateParseError`](#templateparseerror) +- [`TemplateAnalysisError`](#templateanalysiserror) + - [Properties](#properties) + - [`toJSON()` for API Responses](#tojson-for-api-responses) +- [`TemplateRuntimeError`](#templateruntimeerror) +- [`UnsupportedSchemaError`](#unsupportedschemaerror) +- [Diagnostics](#diagnostics) + - [Diagnostic Structure](#diagnostic-structure) + - [Diagnostic Codes](#diagnostic-codes) +- [Syntax Validation](#syntax-validation) +- [Error vs. Diagnostic](#error-vs-diagnostic) + +--- + +## Error Hierarchy + +``` +TemplateError (base) +├── TemplateParseError — invalid Handlebars syntax +├── TemplateAnalysisError — static analysis failed (with diagnostics) +├── TemplateRuntimeError — runtime execution failure +└── UnsupportedSchemaError — schema uses unsupported features (e.g. if/then/else) +``` + +All error classes are exported from `typebars`: + +```ts +import { + TemplateError, + TemplateParseError, + TemplateAnalysisError, + TemplateRuntimeError, + UnsupportedSchemaError, +} from "typebars"; +``` + +--- + +## `TemplateParseError` + +Thrown when the template has invalid Handlebars syntax. This happens during `parse()`, `analyze()`, `execute()`, or `compile()`. + +```ts +try { + engine.execute("{{#if}}unclosed", {}); +} catch (err) { + if (err instanceof TemplateParseError) { + err.message; // → "Parse error: ..." + err.loc; // → { line: number, column: number } (if available) + } +} +``` + +Common causes: +- Unclosed block helpers (`{{#if}}` without `{{/if}}`) +- Mismatched block helpers (`{{#if}}...{{/unless}}`) +- Invalid Handlebars syntax + +--- + +## `TemplateAnalysisError` + +Thrown when `execute()` is called with a `schema` option and the template fails validation. This error wraps the full list of [diagnostics](#diagnostics) from the static analysis. + +```ts +try { + engine.execute("{{unknown}}", data, { + schema: { type: "object", properties: { name: { type: "string" } } }, + }); +} catch (err) { + if (err instanceof TemplateAnalysisError) { + err.diagnostics; // TemplateDiagnostic[] — all diagnostics + err.errors; // TemplateDiagnostic[] — only severity: "error" + err.warnings; // TemplateDiagnostic[] — only severity: "warning" + err.errorCount; // number + err.warningCount; // number + } +} +``` + +### Properties + +| Property | Type | Description | +|----------|------|-------------| +| `diagnostics` | `TemplateDiagnostic[]` | All diagnostics (errors + warnings) | +| `errors` | `TemplateDiagnostic[]` | Only diagnostics with `severity: "error"` | +| `warnings` | `TemplateDiagnostic[]` | Only diagnostics with `severity: "warning"` | +| `errorCount` | `number` | Number of errors | +| `warningCount` | `number` | Number of warnings | + +### `toJSON()` for API Responses + +The `toJSON()` method produces a clean, serializable structure suitable for HTTP API responses: + +```ts +try { + engine.execute("{{unknown}}", data, { schema }); +} catch (err) { + if (err instanceof TemplateAnalysisError) { + // Express / Hono / Fastify / etc. + res.status(400).json(err.toJSON()); + } +} +``` + +The output structure: + +```ts +{ + name: "TemplateAnalysisError", + message: "Static analysis failed with 1 error(s): ...", + errorCount: 1, + warningCount: 0, + diagnostics: [ + { + severity: "error", + code: "UNKNOWN_PROPERTY", + message: "Property \"unknown\" does not exist ...", + loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 11 } }, + source: "unknown", + details: { path: "unknown", availableProperties: ["name"] }, + }, + ], +} +``` + +--- + +## `TemplateRuntimeError` + +Thrown when the template execution fails at runtime (after parsing and optional analysis have succeeded). This covers Handlebars runtime errors and internal execution failures. + +```ts +try { + engine.execute(someTemplate, data); +} catch (err) { + if (err instanceof TemplateRuntimeError) { + err.message; // Description of the runtime failure + } +} +``` + +--- + +## `UnsupportedSchemaError` + +Thrown when the input schema uses features that Typebars intentionally does not support. Currently, this applies to JSON Schema `if`/`then`/`else` conditional schemas. + +See [Conditional Schemas](schema-features.md#conditional-schemas-ifthenelse) for details on this design decision. + +```ts +try { + engine.analyze("{{name}}", { + type: "object", + if: { properties: { type: { const: "admin" } } }, + then: { properties: { level: { type: "number" } } }, + else: { properties: { level: { type: "string" } } }, + }); +} catch (err) { + if (err instanceof UnsupportedSchemaError) { + err.message; // → "Conditional schemas (if/then/else) are not supported ..." + } +} +``` + +> **Recommendation:** Use `oneOf`, `anyOf`, or `allOf` [combinators](schema-features.md#combinators-allof-anyof-oneof) instead of `if`/`then`/`else`. + +--- + +## Diagnostics + +Diagnostics are structured objects produced by the [static analyzer](static-analysis.md). They are returned in `AnalysisResult.diagnostics` and wrapped in `TemplateAnalysisError.diagnostics`. + +### Diagnostic Structure + +```ts +interface TemplateDiagnostic { + severity: "error" | "warning"; + code: DiagnosticCode; + message: string; + loc?: { + start: { line: number; column: number }; + end: { line: number; column: number }; + }; + source?: string; + details?: { + path?: string; + helperName?: string; + expected?: string; + actual?: string; + availableProperties?: string[]; + identifier?: number; + }; +} +``` + +| Field | Description | +|-------|-------------| +| `severity` | `"error"` blocks execution (when using schema validation); `"warning"` is informational | +| `code` | Machine-readable [diagnostic code](#diagnostic-codes) | +| `message` | Human-readable error description | +| `loc` | Source location in the template (line and column, 1-based) | +| `source` | The original expression text (e.g. `"unknown"`, `"badProp"`) | +| `details` | Structured context — varies by diagnostic code | + +### Diagnostic Codes + +| Code | Severity | Description | Details | +|------|----------|-------------|---------| +| `UNKNOWN_PROPERTY` | error | Property doesn't exist in the schema | `path`, `availableProperties` | +| `TYPE_MISMATCH` | error | Incompatible type (e.g. `{{#each}}` on a non-array, or wrong helper argument type) | `expected`, `actual`, `helperName` | +| `MISSING_ARGUMENT` | error | Block helper or registered helper used without a required argument | `helperName` | +| `UNKNOWN_HELPER` | warning | Unknown block helper (neither built-in nor registered) | `helperName` | +| `UNANALYZABLE` | warning | Expression can't be statically analyzed | — | +| `MISSING_IDENTIFIER_SCHEMAS` | error | `{{key:N}}` syntax used but no `identifierSchemas` provided | — | +| `UNKNOWN_IDENTIFIER` | error | Identifier N not found in the provided `identifierSchemas` | `identifier` | +| `IDENTIFIER_PROPERTY_NOT_FOUND` | error | Property doesn't exist in the identifier's schema | `path`, `identifier` | +| `PARSE_ERROR` | error | Invalid Handlebars syntax | — | +| `ROOT_PATH_TRAVERSAL` | error | `$root` used with path traversal (e.g. `$root.name`) | `path` | + +For identifier-related diagnostics, see [Template Identifiers — Identifier Diagnostics](identifiers.md#identifier-diagnostics). + +For `ROOT_PATH_TRAVERSAL`, see [Advanced Features — `$root` Token](advanced.md#root-token). + +--- + +## Syntax Validation + +For live editors or quick checks, use `isValidSyntax()` to verify Handlebars syntax **without** providing a schema: + +```ts +engine.isValidSyntax("Hello {{name}}"); // true +engine.isValidSyntax("{{#if x}}yes{{/if}}"); // true +engine.isValidSyntax("{{#if x}}oops{{/unless}}"); // false — mismatched block +engine.isValidSyntax("{{#if}}unclosed"); // false — missing close tag +``` + +This method only checks syntax — it does **not** validate property names, types, or any schema-related constraints. For full validation, use [`analyze()`](api-reference.md#methods) or [`validate()`](api-reference.md#methods). + +--- + +## Error vs. Diagnostic + +It's important to understand the distinction: + +| Concept | When | How | +|---------|------|-----| +| **Diagnostic** | Returned by `analyze()`, `validate()`, `analyzeAndExecute()` | Part of `AnalysisResult.diagnostics`. Non-throwing — you inspect the result | +| **Error (thrown)** | Thrown by `execute()` when a `schema` option is provided and analysis fails | `TemplateAnalysisError` wraps the diagnostics | +| **Error (thrown)** | Thrown by any method on invalid syntax | `TemplateParseError` | +| **Error (thrown)** | Thrown on unsupported schema features | `UnsupportedSchemaError` | + +In other words: +- **`analyze()` never throws** on validation failures — it returns `{ valid: false, diagnostics: [...] }` +- **`execute()` with a `schema` option throws** a `TemplateAnalysisError` if analysis fails +- **`execute()` without a `schema` option** does not run static analysis and will not throw analysis errors + +```ts +// Non-throwing — inspect the result +const result = engine.analyze("{{unknown}}", schema); +if (!result.valid) { + console.log(result.diagnostics); // Handle diagnostics programmatically +} + +// Throwing — catches errors +try { + engine.execute("{{unknown}}", data, { schema }); +} catch (err) { + if (err instanceof TemplateAnalysisError) { + // Same diagnostics, but thrown as an error + console.log(err.diagnostics); + } +} +``` + +--- + +## What's Next? + +- **[Static Analysis](static-analysis.md)** — how diagnostics are produced and what they mean +- **[Execution](execution.md)** — when errors are thrown during execution +- **[Advanced Features](advanced.md)** — `$root` token and `ROOT_PATH_TRAVERSAL` +- **[API Reference](api-reference.md)** — full method signatures and error class exports \ No newline at end of file diff --git a/docs/execution.md b/docs/execution.md new file mode 100644 index 0000000..4fd52a3 --- /dev/null +++ b/docs/execution.md @@ -0,0 +1,186 @@ +# Execution & Compiled Templates + +> **[← Back to README](../README.md)** | **Related:** [Static Analysis](static-analysis.md) · [Templates](templates.md) · [API Reference](api-reference.md) + +Typebars preserves types at execution time. Unlike standard Handlebars (which always returns strings), Typebars returns the **raw value** when possible — numbers stay numbers, booleans stay booleans, arrays stay arrays. + +--- + +## Table of Contents + +- [Type Preservation](#type-preservation) +- [Execution Modes](#execution-modes) + - [Single Expression](#single-expression) + - [Fast-Path](#fast-path) + - [Single Block](#single-block) + - [Mixed Template](#mixed-template) +- [Literal Passthrough](#literal-passthrough) +- [Compiled Templates](#compiled-templates) + - [Basic Usage](#basic-usage) + - [Object and Literal Compilation](#object-and-literal-compilation) + - [Analysis on Compiled Templates](#analysis-on-compiled-templates) + +--- + +## Type Preservation + +The return type of `execute()` depends on the template structure: + +| Template Shape | Execution Return Type | +|---|---| +| Single expression `{{expr}}` | Raw value (`number`, `boolean`, `object`, `array`, `null`…) | +| Mixed template `text {{expr}}` | `string` (concatenation) | +| Single block with literal branches | Coerced value (`number`, `boolean`, `null`) | +| Multi-block or mixed | `string` | +| Literal input (`42`, `true`, `null`) | The value as-is | + +```ts +const engine = new Typebars(); +const data = { name: "Alice", age: 30, active: true, tags: ["ts", "js"] }; + +// Single expression → raw type +engine.execute("{{age}}", data); // → 30 (number) +engine.execute("{{active}}", data); // → true (boolean) +engine.execute("{{tags}}", data); // → ["ts", "js"] (array) + +// Mixed → string +engine.execute("Age: {{age}}", data); // → "Age: 30" (string) + +// Single block with literal branches → coerced +engine.execute("{{#if active}}42{{else}}0{{/if}}", data); // → 42 (number) +engine.execute("{{#if active}}true{{else}}false{{/if}}", data); // → true (boolean) + +// Literal passthrough +engine.execute(42, data); // → 42 +engine.execute(true, data); // → true +engine.execute(null, data); // → null +``` + +This means the **output schema** inferred at [analysis time](static-analysis.md#output-schema-inference) matches the actual runtime value type. + +--- + +## Execution Modes + +Internally, Typebars uses four execution modes, ordered from fastest to most general. The engine automatically selects the best mode based on the template structure. + +### Single Expression + +When the template is a single `{{expression}}` (with optional surrounding whitespace), the executor **bypasses Handlebars entirely** and resolves the value directly from the data object. This is the fastest path and preserves the raw type. + +```ts +engine.execute("{{age}}", { age: 30 }); // → 30 (number — no Handlebars involved) +engine.execute(" {{tags}} ", { tags: [1] }); // → [1] (array — whitespace is trimmed) +``` + +This also applies to helpers that return non-primitive values: + +```ts +engine.execute('{{map users "name"}}', { users: [{ name: "Alice" }, { name: "Bob" }] }); +// → ["Alice", "Bob"] (array — bypasses Handlebars, direct execution) +``` + +### Fast-Path + +A fast-path optimization is used for simple templates that can be resolved without full Handlebars compilation. The parser detects these patterns and the executor handles them with string concatenation. + +### Single Block + +When the template is a single block helper (`{{#if}}`, `{{#unless}}`, `{{#with}}`), the executor evaluates the block and attempts to **coerce the result** back to a typed value: + +```ts +engine.execute("{{#if active}}42{{else}}0{{/if}}", { active: true }); +// → 42 (number — the string "42" is coerced back to a number) + +engine.execute("{{#if active}}null{{else}}fallback{{/if}}", { active: true }); +// → null (the string "null" is coerced to null) +``` + +### Mixed Template + +For templates with text + expressions, multiple blocks, or any complex structure, the executor falls back to standard Handlebars compilation. The result is always a `string`: + +```ts +engine.execute("Hello {{name}}, you are {{age}}", data); +// → "Hello Alice, you are 30" (string) +``` + +--- + +## Literal Passthrough + +Non-string inputs (`number`, `boolean`, `null`) bypass the template engine entirely and are returned as-is: + +```ts +engine.execute(42, {}); // → 42 +engine.execute(true, {}); // → true +engine.execute(null, {}); // → null +``` + +This is particularly useful in [object templates](templates.md#object-templates) where some properties are fixed values alongside dynamic templates. + +--- + +## Compiled Templates + +For templates executed multiple times with different data, `compile()` parses the template **once** and returns a reusable `CompiledTemplate`. This avoids re-parsing and re-compiling on every call. + +### Basic Usage + +```ts +const engine = new Typebars(); +const tpl = engine.compile("Hello {{name}}!"); + +// No re-parsing — execute many times with different data +tpl.execute({ name: "Alice" }); // → "Hello Alice!" +tpl.execute({ name: "Bob" }); // → "Hello Bob!" +``` + +### Object and Literal Compilation + +Object templates and literal values can also be compiled: + +```ts +const tpl = engine.compile({ + userName: "{{name}}", + userAge: "{{age}}", + fixed: 42, +}); + +tpl.execute(data); +// → { userName: "Alice", userAge: 30, fixed: 42 } +``` + +The compiled template uses a discriminated union internally (`TemplateState`) with kinds: `"template"`, `"literal"`, `"object"`, and `"array"`. + +### Analysis on Compiled Templates + +`CompiledTemplate` supports the same analysis methods as the engine — without re-parsing: + +```ts +const tpl = engine.compile("{{age}}"); + +// Analyze +tpl.analyze(schema); +// → { valid: true, outputSchema: { type: "number" }, diagnostics: [] } + +// Validate (no outputSchema) +tpl.validate(schema); +// → { valid: true, diagnostics: [] } + +// Both at once +const { analysis, value } = tpl.analyzeAndExecute(schema, data); +// analysis.outputSchema → { type: "number" } +// value → 30 +``` + +All [advanced options](advanced.md) (`coerceSchema`, `excludeTemplateExpression`, `identifierSchemas`) work with compiled templates as well. + +--- + +## What's Next? + +- **[Templates](templates.md)** — object templates, array templates, and block helpers +- **[Built-in & Custom Helpers](helpers.md)** — math, logical, comparison, map, and custom helpers +- **[Advanced Features](advanced.md)** — `coerceSchema`, `excludeTemplateExpression`, `$root` token +- **[API Reference](api-reference.md)** — full method signatures for `execute()`, `compile()`, and `CompiledTemplate` diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..eacf9f0 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,115 @@ +# Getting Started + +> **[← Back to README](../README.md)** + +## Installation + +```sh +npm install typebars +# or +yarn add typebars +# or +pnpm add typebars +# or +bun add typebars +``` + +**Peer dependency:** TypeScript ≥ 5 + +--- + +## Quick Start + +```ts +import { Typebars } from "typebars"; + +const engine = new Typebars(); + +const schema = { + type: "object", + properties: { + name: { type: "string" }, + age: { type: "number" }, + }, + required: ["name", "age"], +}; + +const data = { name: "Alice", age: 30 }; + +// 1. Analyze — validate + infer output type +const analysis = engine.analyze("Hello {{name}}", schema); +// analysis.valid → true +// analysis.outputSchema → { type: "string" } + +// 2. Execute — render the template +const result = engine.execute("Hello {{name}}", data); +// result → "Hello Alice" + +// 3. Or do both at once +const { analysis: a, value } = engine.analyzeAndExecute("{{age}}", schema, data); +// a.outputSchema → { type: "number" } +// value → 30 +``` + +--- + +## How It Works + +Typebars operates in three phases: + +``` + ┌────────────────────────────────────────────┐ + │ Input Schema │ + │ (JSON Schema describing available data) │ + └──────────────────┬─────────────────────────┘ + │ +┌──────────────┐ ┌───────────────────▼─────────────────────────┐ +│ Template │───▶│ Static Analyzer │ +│ (string) │ │ │ +└──────────────┘ │ 1. Validates every {{expression}} against │ + │ the input schema │ + │ 2. Validates block helper usage (#if on │ + │ existing property, #each on arrays...) │ + │ 3. Infers the output JSON Schema from the │ + │ template structure │ + │ │ + └──────┬───────────────────┬──────────────────┘ + │ │ + ┌────────────▼──┐ ┌──────────▼──────────┐ + │ Diagnostics │ │ Output Schema │ + │ (errors, │ │ (JSON Schema of │ + │ warnings) │ │ the return value) │ + └───────────────┘ └─────────────────────┘ +``` + +The **input schema** describes what variables are available. The **output schema** describes what the template will produce. The analyzer derives the output from the input — purely statically, without executing anything. + +### The Three Core Operations + +| Operation | Description | Returns | +|-----------|-------------|---------| +| `analyze()` | Validates the template and infers the output type | `AnalysisResult` with `valid`, `diagnostics`, `outputSchema` | +| `execute()` | Renders the template with data | The result value (type-preserved) | +| `analyzeAndExecute()` | Both in one call | `{ analysis, value }` | + +### Template Input Types + +Typebars doesn't just accept strings. The engine accepts a `TemplateInput` union type: + +| Input type | Behavior | +|------------|----------| +| `string` | Standard Handlebars template — parsed and executed | +| `number` | Literal passthrough (e.g. `42` → `42`) | +| `boolean` | Literal passthrough (e.g. `true` → `true`) | +| `null` | Literal passthrough (`null` → `null`) | +| `TemplateInputObject` | Object where each property is a `TemplateInput` — see [Templates](templates.md) | +| `TemplateInputArray` | Array where each element is a `TemplateInput` — see [Templates](templates.md) | + +--- + +## What's Next? + +- **[Static Analysis](static-analysis.md)** — learn how input validation and output schema inference work +- **[Templates](templates.md)** — object templates, array templates, and block helpers +- **[Built-in & Custom Helpers](helpers.md)** — math, logical, comparison, map, and custom helpers +- **[API Reference](api-reference.md)** — full API documentation \ No newline at end of file diff --git a/docs/helpers.md b/docs/helpers.md new file mode 100644 index 0000000..e46bb65 --- /dev/null +++ b/docs/helpers.md @@ -0,0 +1,578 @@ +# Built-in & Custom Helpers + +> **[← Back to README](../README.md)** | **Related:** [Templates](templates.md) · [Static Analysis](static-analysis.md) · [Execution](execution.md) · [API Reference](api-reference.md) + +Typebars pre-registers a comprehensive set of helpers on every engine instance: **math**, **logical/comparison**, and **map** helpers. All are fully integrated with the static analyzer — argument types are validated, missing properties are caught, and the output schema is correctly inferred. + +You can also register your own **custom helpers** with type metadata for full static analysis support. + +--- + +## Table of Contents + +- [Math Helpers](#math-helpers) + - [Named Operators](#named-operators) + - [Unary Functions](#unary-functions) + - [Generic `math` Helper](#generic-math-helper) + - [Static Analysis of Math Helpers](#static-analysis-of-math-helpers) +- [Logical & Comparison Helpers](#logical--comparison-helpers) + - [Why Sub-Expressions?](#why-sub-expressions) + - [Comparison Helpers](#comparison-helpers) + - [Equality Helpers](#equality-helpers) + - [Logical Operators](#logical-operators) + - [Collection Helpers](#collection-helpers) + - [Generic `compare` Helper](#generic-compare-helper) + - [Nested Sub-Expressions](#nested-sub-expressions) + - [Static Analysis of Sub-Expressions](#static-analysis-of-sub-expressions) +- [Map Helper](#map-helper) + - [Basic Usage](#basic-usage) + - [Chaining](#chaining) + - [Static Analysis of Map](#static-analysis-of-map) +- [Custom Helpers](#custom-helpers) + - [`registerHelper`](#registerhelper) + - [`defineHelper` (Type-Safe)](#definehelper-type-safe) + - [Helper Management](#helper-management) + +--- + +## Math Helpers + +Pre-registered on every `Typebars` instance. All return `{ type: "number" }` for static analysis. + +### Named Operators + +Binary operators that take two numeric arguments: + +| Helper | Aliases | Usage | Example | +|--------|---------|-------|---------| +| `add` | — | `{{add a b}}` | `{{add price tax}}` → 121 | +| `subtract` | `sub` | `{{sub a b}}` | `{{sub price discount}}` → 80 | +| `multiply` | `mul` | `{{mul a b}}` | `{{mul price quantity}}` → 300 | +| `divide` | `div` | `{{div a b}}` | `{{div total count}}` → 33.3 | +| `modulo` | `mod` | `{{mod a b}}` | `{{mod 10 3}}` → 1 | +| `pow` | — | `{{pow a b}}` | `{{pow 2 10}}` → 1024 | +| `min` | — | `{{min a b}}` | `{{min a b}}` → smaller | +| `max` | — | `{{max a b}}` | `{{max a b}}` → larger | + +### Unary Functions + +Functions that take a single numeric argument (and an optional second parameter for `round`): + +| Helper | Usage | Description | +|--------|-------|-------------| +| `abs` | `{{abs value}}` | Absolute value | +| `ceil` | `{{ceil value}}` | Round up | +| `floor` | `{{floor value}}` | Round down | +| `round` | `{{round value [precision]}}` | Round with optional decimal places | +| `sqrt` | `{{sqrt value}}` | Square root | + +```ts +engine.execute("{{round pi 2}}", { pi: 3.14159 }); // → 3.14 +engine.execute("{{abs value}}", { value: -7 }); // → 7 +``` + +Math helpers work with [array `.length` intrinsic](schema-features.md#array-length-intrinsic): + +```ts +engine.execute("{{div items.length count}}", { items: [1, 2, 3, 4, 5], count: 2 }); +// → 2.5 +``` + +### Generic `math` Helper + +Inline arithmetic with the operator as a string: + +```ts +engine.execute('{{math a "+" b}}', { a: 10, b: 3 }); // → 13 +engine.execute('{{math a "*" b}}', { a: 10, b: 3 }); // → 30 +engine.execute('{{math a "**" b}}', { a: 2, b: 10 }); // → 1024 +``` + +Supported operators: `+`, `-`, `*`, `/`, `%`, `**` + +### Static Analysis of Math Helpers + +All math helpers validate that parameters resolve to `{ type: "number" }` and infer `{ type: "number" }` as output: + +```ts +const schema = { + type: "object", + properties: { + a: { type: "number" }, + b: { type: "number" }, + label: { type: "string" }, + }, +}; + +// ✅ Valid +const { analysis, value } = engine.analyzeAndExecute( + "{{add a b}}", + schema, + { a: 10, b: 3 }, +); +analysis.outputSchema; // → { type: "number" } +value; // → 13 + +// ⚠️ Type mismatch on parameter +const { analysis: a2 } = engine.analyzeAndExecute( + "{{add a label}}", + schema, + { a: 10, label: "hello" }, +); +// a2.valid → false (string passed to a number parameter) +``` + +--- + +## Logical & Comparison Helpers + +Pre-registered on every `Typebars` instance. All return `{ type: "boolean" }` for static analysis. + +These helpers enable **conditional logic** inside templates via Handlebars [sub-expressions](https://handlebarsjs.com/guide/subexpressions.html) — the `(helper arg1 arg2)` syntax used as arguments to [block helpers](templates.md#block-helpers) like `{{#if}}` and `{{#unless}}`. + +### Why Sub-Expressions? + +Standard Handlebars only supports simple truthiness checks: + +```handlebars +{{!-- Native Handlebars: can only test if "active" is truthy --}} +{{#if active}}yes{{else}}no{{/if}} +``` + +There is **no built-in way** to compare values, combine conditions, or negate expressions. Handlebars deliberately delegates this to helpers. + +Typebars ships a complete set of logical and comparison helpers that unlock expressive conditions out of the box: + +```handlebars +{{!-- Typebars: compare, combine, negate — all statically analyzed --}} +{{#if (gt age 18)}}adult{{else}}minor{{/if}} +{{#if (and active (eq role "admin"))}}full access{{/if}} +{{#if (not suspended)}}welcome{{/if}} +``` + +These helpers are **fully integrated with the static analyzer**: argument types are validated, missing properties are caught, and the [output schema](static-analysis.md#single-block--branch-type-inference) is correctly inferred from the branches — not from the boolean condition. + +### Comparison Helpers + +| Helper | Aliases | Usage | Description | +|--------|---------|-------|-------------| +| `lt` | — | `(lt a b)` | `a < b` (numeric) | +| `lte` | `le` | `(lte a b)` | `a <= b` (numeric) | +| `gt` | — | `(gt a b)` | `a > b` (numeric) | +| `gte` | `ge` | `(gte a b)` | `a >= b` (numeric) | + +Both parameters must resolve to `{ type: "number" }`. A type mismatch is reported as an error: + +```ts +const schema = { + type: "object", + properties: { + age: { type: "number" }, + score: { type: "number" }, + name: { type: "string" }, + account: { + type: "object", + properties: { balance: { type: "number" } }, + }, + }, +}; + +// ✅ Both arguments are numbers +engine.analyze("{{#if (lt age 18)}}minor{{else}}adult{{/if}}", schema); +// valid: true, no diagnostics + +// ✅ Nested property access works +engine.analyze("{{#if (lt account.balance 500)}}low{{else}}ok{{/if}}", schema); +// valid: true + +// ✅ Number literals are accepted +engine.analyze("{{#if (gte score 90)}}A{{else}}B{{/if}}", schema); +// valid: true + +// ❌ String where number is expected → TYPE_MISMATCH +engine.analyze("{{#if (lt name 500)}}yes{{/if}}", schema); +// valid: false — "name" is string, "lt" expects number +``` + +### Equality Helpers + +| Helper | Aliases | Usage | Description | +|--------|---------|-------|-------------| +| `eq` | — | `(eq a b)` | Strict equality (`===`) | +| `ne` | `neq` | `(ne a b)` | Strict inequality (`!==`) | + +These accept any type — no type constraint on parameters: + +```ts +// String comparison +engine.execute('{{#if (eq role "admin")}}yes{{else}}no{{/if}}', { role: "admin" }); +// → "yes" + +// Number comparison +engine.execute("{{#if (ne score 0)}}scored{{else}}zero{{/if}}", { score: 85 }); +// → "scored" +``` + +### Logical Operators + +| Helper | Usage | Description | +|--------|-------|-------------| +| `not` | `(not value)` | Logical negation — `true` if value is falsy | +| `and` | `(and a b)` | Logical AND — `true` if both are truthy | +| `or` | `(or a b)` | Logical OR — `true` if at least one is truthy | + +```ts +engine.execute("{{#if (not active)}}inactive{{else}}active{{/if}}", { active: false }); +// → "inactive" + +engine.execute( + "{{#if (and active premium)}}VIP{{else}}standard{{/if}}", + { active: true, premium: true }, +); +// → "VIP" + +engine.execute( + "{{#if (or isAdmin isModerator)}}staff{{else}}user{{/if}}", + { isAdmin: false, isModerator: true }, +); +// → "staff" +``` + +### Collection Helpers + +| Helper | Usage | Description | +|--------|-------|-------------| +| `contains` | `(contains haystack needle)` | `true` if the string contains the substring, or the array contains the element | +| `in` | `(in value ...candidates)` | `true` if value is one of the candidates (variadic) | + +```ts +engine.execute( + '{{#if (contains name "ali")}}match{{else}}no match{{/if}}', + { name: "Alice" }, +); +// → "match" + +engine.execute( + '{{#if (in status "active" "pending")}}ok{{else}}blocked{{/if}}', + { status: "active" }, +); +// → "ok" +``` + +### Generic `compare` Helper + +A single helper with the operator as a string parameter: + +```ts +engine.execute('{{#if (compare a "<" b)}}yes{{else}}no{{/if}}', { a: 3, b: 10 }); +// → "yes" + +engine.execute('{{#if (compare name "===" "Alice")}}hi Alice{{/if}}', { name: "Alice" }); +// → "hi Alice" +``` + +Supported operators: `==`, `===`, `!=`, `!==`, `<`, `<=`, `>`, `>=` + +### Nested Sub-Expressions + +Sub-expressions can be **nested** to build complex conditions. Each level is fully analyzed: + +```ts +// AND + comparison +engine.execute( + '{{#if (and (eq role "admin") (gt score 90))}}top admin{{else}}other{{/if}}', + { role: "admin", score: 95 }, +); +// → "top admin" + +// OR + NOT +engine.execute( + "{{#if (or (not active) (lt score 10))}}alert{{else}}ok{{/if}}", + { active: true, score: 85 }, +); +// → "ok" + +// Deeply nested +engine.execute( + '{{#if (and (or (lt age 18) (gt age 65)) (eq role "special"))}}discount{{else}}full price{{/if}}', + { age: 70, role: "special" }, +); +// → "discount" +``` + +### Static Analysis of Sub-Expressions + +Sub-expressions are **fully integrated** with the static analyzer. The key behaviors: + +**1. Argument validation** — every argument is resolved against the schema: + +```ts +// ❌ Unknown property in sub-expression argument +engine.analyze("{{#if (lt nonExistent 500)}}yes{{/if}}", schema); +// valid: false — UNKNOWN_PROPERTY + +// ❌ Missing nested property +engine.analyze("{{#if (lt account.foo 500)}}yes{{/if}}", schema); +// valid: false — UNKNOWN_PROPERTY + +// ❌ Too few arguments +engine.analyze("{{#if (lt age)}}yes{{/if}}", schema); +// valid: false — MISSING_ARGUMENT +``` + +**2. Type checking** — parameter types are validated against helper declarations: + +```ts +// ❌ String where number is expected +engine.analyze("{{#if (lt name 500)}}yes{{/if}}", schema); +// valid: false — TYPE_MISMATCH: "lt" parameter "a" expects number, got string +``` + +**3. Output type inference** — the output schema is based on the **branches**, not the condition: + +```ts +// The condition (lt ...) returns boolean, but the output type +// comes from the branch content: + +engine.analyze("{{#if (lt age 18)}}{{name}}{{else}}{{age}}{{/if}}", schema).outputSchema; +// → { oneOf: [{ type: "string" }, { type: "number" }] } +// (NOT boolean — the condition type doesn't leak into the output) + +engine.analyze("{{#if (gt score 50)}}{{age}}{{else}}{{score}}{{/if}}", schema).outputSchema; +// → { type: "number" } +// (both branches are number → simplified to single type) + +engine.analyze("{{#if (eq age 18)}}42{{else}}true{{/if}}", schema).outputSchema; +// → { oneOf: [{ type: "number" }, { type: "boolean" }] } + +// Chained else-if pattern +engine.analyze( + "{{#if (lt age 18)}}minor{{else}}{{#if (lt age 65)}}adult{{else}}senior{{/if}}{{/if}}", + schema, +).outputSchema; +// → { type: "string" } +// (all branches are string literals → simplified) +``` + +**4. Unknown helpers** — unregistered helpers emit a warning (not an error): + +```ts +engine.analyze("{{#if (myCustomCheck age)}}yes{{/if}}", schema); +// valid: true, but 1 warning: UNKNOWN_HELPER "myCustomCheck" +``` + +--- + +## Map Helper + +The `map` helper extracts a specific property from each element of an array, returning a new array of those values. It is pre-registered on every `Typebars` instance. + +### Basic Usage + +```ts +const data = { + users: [ + { name: "Alice", age: 30 }, + { name: "Bob", age: 25 }, + { name: "Charlie", age: 35 }, + ], +}; + +engine.execute('{{map users "name"}}', data); +// → ["Alice", "Bob", "Charlie"] + +engine.execute('{{map users "age"}}', data); +// → [30, 25, 35] +``` + +The first argument must be an array of objects, and the second argument must be a **quoted string literal** (the property name to extract). + +> **Type preservation:** In [single expression mode](execution.md#single-expression), `map` returns a raw array. In a mixed template, the array is joined with `", "` into a string. + +### Chaining + +The `map` helper can be chained via sub-expressions to drill into nested arrays: + +```ts +const data = { + users: [ + { name: "Alice", cartItems: [{ productId: "P1" }, { productId: "P2" }] }, + { name: "Bob", cartItems: [{ productId: "P3" }] }, + ], +}; + +// First map extracts cartItems (array of arrays), then second map extracts productId +engine.execute('{{map (map users "cartItems") "productId"}}', data); +// → ["P1", "P2", "P3"] +``` + +The inner `map` returns arrays of `cartItems` which are flattened one level before the outer `map` extracts `productId`. + +### Static Analysis of Map + +The `map` helper has special static analysis handling: + +- The first argument must resolve to an array of objects +- The second argument must be a quoted string literal (e.g. `"name"`, not `name`) +- The property must exist in the item schema of the array +- The inferred return type is `{ type: "array", items: }` + +```ts +const schema = { + type: "object", + properties: { + users: { + type: "array", + items: { + type: "object", + properties: { + name: { type: "string" }, + age: { type: "number" }, + }, + }, + }, + }, +}; + +// ✅ Valid — "name" exists in the item schema +engine.analyze('{{map users "name"}}', schema); +// → valid: true, outputSchema: { type: "array", items: { type: "string" } } + +// ✅ Number property +engine.analyze('{{map users "age"}}', schema); +// → valid: true, outputSchema: { type: "array", items: { type: "number" } } +``` + +--- + +## Custom Helpers + +### `registerHelper` + +Register a custom helper with type metadata for static analysis: + +```ts +const engine = new Typebars(); + +engine.registerHelper("uppercase", { + fn: (value) => String(value).toUpperCase(), + params: [ + { name: "value", type: { type: "string" }, description: "The string to convert" }, + ], + returnType: { type: "string" }, + description: "Converts to UPPERCASE", +}); + +// Execution +engine.execute("{{uppercase name}}", { name: "alice" }); +// → "ALICE" + +// Static analysis uses the declared returnType +engine.analyze("{{uppercase name}}", { + type: "object", + properties: { name: { type: "string" } }, +}).outputSchema; +// → { type: "string" } +``` + +Helpers can also be passed at construction time: + +```ts +const engine = new Typebars({ + helpers: [ + { + name: "uppercase", + fn: (value) => String(value).toUpperCase(), + params: [{ name: "value", type: { type: "string" } }], + returnType: { type: "string" }, + }, + { + name: "double", + fn: (value) => Number(value) * 2, + params: [{ name: "value", type: { type: "number" } }], + returnType: { type: "number" }, + }, + ], +}); +``` + +`registerHelper` returns `this` for chaining: + +```ts +engine + .registerHelper("upper", { fn: (v) => String(v).toUpperCase(), returnType: { type: "string" } }) + .registerHelper("lower", { fn: (v) => String(v).toLowerCase(), returnType: { type: "string" } }); +``` + +### `defineHelper` (Type-Safe) + +`defineHelper()` infers the TypeScript types of your `fn` arguments from the JSON Schemas declared in `params`. This gives you full type safety in the helper implementation: + +```ts +import { Typebars, defineHelper } from "typebars"; + +const concatHelper = defineHelper({ + name: "concat", + description: "Concatenates two strings", + params: [ + { name: "a", type: { type: "string" }, description: "First string" }, + { name: "b", type: { type: "string" }, description: "Second string" }, + { name: "sep", type: { type: "string" }, description: "Separator", optional: true }, + ] as const, + fn: (a, b, sep) => { + // TypeScript infers: a: string, b: string, sep: string | undefined + return `${a}${sep ?? ""}${b}`; + }, + returnType: { type: "string" }, +}); + +const engine = new Typebars({ helpers: [concatHelper] }); +``` + +> **`as const`** on the `params` array is required for TypeScript to infer the parameter types correctly. + +### Helper Management + +| Method | Description | +|--------|-------------| +| `registerHelper(name, definition)` | Register a custom helper. Returns `this` for chaining | +| `unregisterHelper(name)` | Remove a helper (including built-in ones). Returns `this` | +| `hasHelper(name)` | Check if a helper is registered. Returns `boolean` | + +```ts +engine.hasHelper("add"); // true (built-in) +engine.hasHelper("uppercase"); // false (not registered) + +engine.registerHelper("uppercase", { /* ... */ }); +engine.hasHelper("uppercase"); // true + +engine.unregisterHelper("uppercase"); +engine.hasHelper("uppercase"); // false +``` + +> **Note:** Unregistering a helper invalidates the compilation cache to ensure templates are recompiled without the removed helper. + +--- + +## Summary of Built-in Helpers + +| Category | Helpers | Output Schema | +|----------|---------|---------------| +| **Math (binary)** | `add`, `sub`, `mul`, `div`, `mod`, `pow`, `min`, `max` | `{ type: "number" }` | +| **Math (unary)** | `abs`, `ceil`, `floor`, `round`, `sqrt` | `{ type: "number" }` | +| **Math (generic)** | `math` | `{ type: "number" }` | +| **Comparison** | `lt`, `lte`/`le`, `gt`, `gte`/`ge` | `{ type: "boolean" }` | +| **Equality** | `eq`, `ne`/`neq` | `{ type: "boolean" }` | +| **Logical** | `not`, `and`, `or` | `{ type: "boolean" }` | +| **Collection** | `contains`, `in` | `{ type: "boolean" }` | +| **Generic compare** | `compare` | `{ type: "boolean" }` | +| **Map** | `map` | `{ type: "array", items: }` | + +--- + +## What's Next? + +- **[Templates](templates.md)** — use helpers inside block helpers and templates +- **[Static Analysis](static-analysis.md)** — how helper arguments and return types are validated +- **[Template Identifiers](identifiers.md)** — the `{{key:N}}` syntax for multi-source pipelines +- **[API Reference](api-reference.md)** — full `HelperDefinition` and `HelperConfig` types \ No newline at end of file diff --git a/docs/identifiers.md b/docs/identifiers.md new file mode 100644 index 0000000..3bb9dae --- /dev/null +++ b/docs/identifiers.md @@ -0,0 +1,217 @@ +# Template Identifiers (`{{key:N}}`) + +> **[← Back to README](../README.md)** | **Related:** [Static Analysis](static-analysis.md) · [Execution](execution.md) · [API Reference](api-reference.md) + +The `{{key:N}}` syntax references variables from **different data sources**, identified by a numeric ID. This is useful in workflow engines, multi-step pipelines, or any scenario where template variables come from multiple independent contexts. + +--- + +## Table of Contents + +- [Overview](#overview) +- [Analysis with Identifier Schemas](#analysis-with-identifier-schemas) +- [Mixing Identifiers and Regular Expressions](#mixing-identifiers-and-regular-expressions) +- [Execution with Identifier Data](#execution-with-identifier-data) +- [`analyzeAndExecute` with Identifiers](#analyzeandexecute-with-identifiers) +- [Identifier Diagnostics](#identifier-diagnostics) + +--- + +## Overview + +In standard Handlebars, all variables come from a single data context: + +```handlebars +Hello {{name}}, your order is {{orderId}}. +``` + +With template identifiers, you can reference variables from **separate data sources** by appending `:N` to the variable name, where `N` is a numeric identifier: + +```handlebars +Hello {{name}}, your meeting is {{meetingId:1}} with lead {{leadName:2}}. +``` + +Here: +- `{{name}}` — resolved from the main `inputSchema` / `data` +- `{{meetingId:1}}` — resolved from identifier **1**'s schema / data +- `{{leadName:2}}` — resolved from identifier **2**'s schema / data + +The identifier is always on the **last path segment**. For example, `{{address.city:1}}` resolves `address.city` from identifier 1's schema. + +--- + +## Analysis with Identifier Schemas + +Each identifier maps to its own JSON Schema. Pass them via the `options` object: + +```ts +const engine = new Typebars(); + +const inputSchema = { type: "object", properties: {} }; + +const identifierSchemas = { + 1: { + type: "object", + properties: { meetingId: { type: "string" } }, + }, + 2: { + type: "object", + properties: { leadName: { type: "string" } }, + }, +}; + +// ✅ Valid — meetingId exists in identifier 1's schema +engine.analyze("{{meetingId:1}}", inputSchema, { identifierSchemas }); +// → valid: true, outputSchema: { type: "string" } + +// ❌ Invalid — identifier 1 doesn't have "badKey" +engine.analyze("{{badKey:1}}", inputSchema, { identifierSchemas }); +// → valid: false, code: IDENTIFIER_PROPERTY_NOT_FOUND + +// ❌ Invalid — identifier 99 doesn't exist +engine.analyze("{{meetingId:99}}", inputSchema, { identifierSchemas }); +// → valid: false, code: UNKNOWN_IDENTIFIER + +// ❌ Invalid — identifiers used but no schemas provided +engine.analyze("{{meetingId:1}}", inputSchema); +// → valid: false, code: MISSING_IDENTIFIER_SCHEMAS +``` + +--- + +## Mixing Identifiers and Regular Expressions + +Regular expressions validate against `inputSchema`, identifier expressions validate against `identifierSchemas`. Both can coexist in the same template: + +```ts +const schema = { + type: "object", + properties: { name: { type: "string" } }, +}; + +const idSchemas = { + 1: { + type: "object", + properties: { meetingId: { type: "string" } }, + }, +}; + +// ✅ "name" validated against schema, "meetingId:1" against idSchemas[1] +engine.analyze("{{name}} — {{meetingId:1}}", schema, { + identifierSchemas: idSchemas, +}); +// → valid: true +``` + +This also works in [object templates](templates.md#object-templates): + +```ts +engine.analyze( + { + userName: "{{name}}", + meeting: "{{meetingId:1}}", + summary: "{{name}} has meeting {{meetingId:1}}", + }, + schema, + { identifierSchemas: idSchemas }, +); +// → valid: true +``` + +--- + +## Execution with Identifier Data + +At execution time, pass `identifierData` in the options. Each key maps an identifier number to its data object: + +```ts +const result = engine.execute( + "Meeting: {{meetingId:1}}, Lead: {{leadName:2}}", + {}, + { + identifierData: { + 1: { meetingId: "MTG-42" }, + 2: { leadName: "Alice" }, + }, + }, +); +// → "Meeting: MTG-42, Lead: Alice" +``` + +[Type preservation](execution.md#type-preservation) works the same way for identifier expressions. A single expression with an identifier returns the raw value: + +```ts +engine.execute("{{count:1}}", {}, { + identifierData: { 1: { count: 42 } }, +}); +// → 42 (number, not string) +``` + +--- + +## `analyzeAndExecute` with Identifiers + +Both `identifierSchemas` (for analysis) and `identifierData` (for execution) are passed in the options: + +```ts +const { analysis, value } = engine.analyzeAndExecute( + "{{total:1}}", + {}, // inputSchema + {}, // data + { + identifierSchemas: { + 1: { type: "object", properties: { total: { type: "number" } } }, + }, + identifierData: { + 1: { total: 99.95 }, + }, + }, +); + +analysis.valid; // true +analysis.outputSchema; // { type: "number" } +value; // 99.95 +``` + +[Compiled templates](execution.md#compiled-templates) also support identifiers through their `analyze()`, `execute()`, and `analyzeAndExecute()` methods. + +--- + +## Identifier Diagnostics + +Three [diagnostic codes](static-analysis.md#diagnostic-codes) are specific to template identifiers: + +| Code | Severity | Description | +|------|----------|-------------| +| `MISSING_IDENTIFIER_SCHEMAS` | error | The `{{key:N}}` syntax is used but no `identifierSchemas` were provided in the options | +| `UNKNOWN_IDENTIFIER` | error | The identifier `N` does not exist in the provided `identifierSchemas` | +| `IDENTIFIER_PROPERTY_NOT_FOUND` | error | The property does not exist in the identifier's schema | + +```ts +// No identifierSchemas provided at all +engine.analyze("{{meetingId:1}}", inputSchema); +// → code: MISSING_IDENTIFIER_SCHEMAS + +// Identifier 99 not found +engine.analyze("{{meetingId:99}}", inputSchema, { + identifierSchemas: { 1: { type: "object", properties: {} } }, +}); +// → code: UNKNOWN_IDENTIFIER, details: { identifier: 99 } + +// Property doesn't exist in identifier's schema +engine.analyze("{{badKey:1}}", inputSchema, { + identifierSchemas: { + 1: { type: "object", properties: { meetingId: { type: "string" } } }, + }, +}); +// → code: IDENTIFIER_PROPERTY_NOT_FOUND, details: { path: "badKey", identifier: 1 } +``` + +--- + +## What's Next? + +- **[Advanced Features](advanced.md)** — `coerceSchema`, `excludeTemplateExpression`, `$root` token +- **[Static Analysis](static-analysis.md)** — full diagnostics reference and output schema inference +- **[Execution](execution.md)** — type preservation and compiled templates +- **[API Reference](api-reference.md)** — full method signatures with identifier options \ No newline at end of file diff --git a/docs/schema-features.md b/docs/schema-features.md new file mode 100644 index 0000000..f2295e2 --- /dev/null +++ b/docs/schema-features.md @@ -0,0 +1,238 @@ +# Schema Features + +> **[← Back to README](../README.md)** | **Related:** [Static Analysis](static-analysis.md) · [API Reference](api-reference.md) + +Typebars works exclusively with **JSON Schema Draft 7** (`JSONSchema7`). This page covers the schema features supported by the static analyzer and schema resolver. + +--- + +## Table of Contents + +- [`$ref` Resolution](#ref-resolution) +- [Combinators (`allOf`, `anyOf`, `oneOf`)](#combinators-allof-anyof-oneof) +- [`additionalProperties`](#additionalproperties) +- [Array `.length` Intrinsic](#array-length-intrinsic) +- [Conditional Schemas (`if`/`then`/`else`)](#conditional-schemas-ifthenelse) + +--- + +## `$ref` Resolution + +Internal `$ref` references (`#/definitions/...` or `#/$defs/...`) are resolved transparently: + +```ts +const schema = { + type: "object", + definitions: { + Address: { + type: "object", + properties: { + street: { type: "string" }, + city: { type: "string" }, + }, + }, + }, + properties: { + home: { $ref: "#/definitions/Address" }, + work: { $ref: "#/definitions/Address" }, + }, +}; + +// ✅ Resolves through $ref +engine.analyze("{{home.city}}", schema); +// → valid: true, outputSchema: { type: "string" } + +// ✅ Works with multiple $ref to the same definition +engine.analyze("{{home.city}} — {{work.street}}", schema); +// → valid: true + +// ❌ Property doesn't exist behind the $ref +engine.analyze("{{home.zip}}", schema); +// → valid: false — "zip" not found in Address +``` + +Nested `$ref` (a `$ref` pointing to another `$ref`) is resolved recursively. + +> **Note:** Only internal references are supported. External references (e.g. `{ "$ref": "https://..." }`) are not resolved. + +--- + +## Combinators (`allOf`, `anyOf`, `oneOf`) + +Properties defined across combinators are resolved by searching all branches: + +### `allOf` + +```ts +const schema = { + type: "object", + allOf: [ + { type: "object", properties: { a: { type: "string" } } }, + { type: "object", properties: { b: { type: "number" } } }, + ], +}; + +engine.analyze("{{a}}", schema).valid; // true → { type: "string" } +engine.analyze("{{b}}", schema).valid; // true → { type: "number" } +``` + +### `anyOf` / `oneOf` + +```ts +const schema = { + type: "object", + oneOf: [ + { type: "object", properties: { x: { type: "string" } } }, + { type: "object", properties: { y: { type: "number" } } }, + ], +}; + +// Properties from any branch are searchable +engine.analyze("{{x}}", schema).valid; // true +engine.analyze("{{y}}", schema).valid; // true +``` + +`anyOf` works the same way — all branches are searched for property resolution. + +### Combinators with `$ref` + +Combinators and `$ref` can be combined. The resolver handles both transparently: + +```ts +const schema = { + type: "object", + definitions: { + Base: { + type: "object", + properties: { id: { type: "number" } }, + }, + }, + allOf: [ + { $ref: "#/definitions/Base" }, + { type: "object", properties: { name: { type: "string" } } }, + ], +}; + +engine.analyze("{{id}}", schema).valid; // true +engine.analyze("{{name}}", schema).valid; // true +``` + +--- + +## `additionalProperties` + +When a property isn't found in `properties`, the resolver checks `additionalProperties`: + +### `additionalProperties: true` + +Any property is allowed, but the type is unknown: + +```ts +engine.analyze("{{anything}}", { type: "object", additionalProperties: true }); +// → valid: true, outputSchema: {} +``` + +### `additionalProperties` with a schema + +Unknown properties resolve to the specified schema: + +```ts +engine.analyze("{{anything}}", { + type: "object", + additionalProperties: { type: "number" }, +}); +// → valid: true, outputSchema: { type: "number" } +``` + +### `additionalProperties: false` + +Unknown properties are rejected: + +```ts +engine.analyze("{{anything}}", { + type: "object", + properties: { name: { type: "string" } }, + additionalProperties: false, +}); +// → valid: false, code: UNKNOWN_PROPERTY +``` + +### Mixed: known + additional properties + +Known properties resolve to their declared type; unknown properties fall back to `additionalProperties`: + +```ts +const schema = { + type: "object", + properties: { + name: { type: "string" }, + }, + additionalProperties: { type: "number" }, +}; + +engine.analyze("{{name}}", schema).outputSchema; +// → { type: "string" } — from properties + +engine.analyze("{{score}}", schema).outputSchema; +// → { type: "number" } — from additionalProperties +``` + +--- + +## Array `.length` Intrinsic + +Accessing `.length` on an array property is valid and inferred as `{ type: "integer" }`: + +```ts +const schema = { + type: "object", + properties: { + tags: { type: "array", items: { type: "string" } }, + orders: { type: "array", items: { type: "object", properties: { id: { type: "number" } } } }, + }, +}; + +engine.analyze("{{tags.length}}", schema).outputSchema; +// → { type: "integer" } + +engine.analyze("{{orders.length}}", schema).outputSchema; +// → { type: "integer" } +``` + +This also works at execution time — the actual `.length` value is returned as a number: + +```ts +engine.execute("{{tags.length}}", { tags: ["a", "b", "c"] }); +// → 3 + +// Useful with math helpers +engine.execute("{{div items.length count}}", { items: [1, 2, 3, 4, 5], count: 2 }); +// → 2.5 +``` + +> **Note:** `.length` on a non-array type is invalid and produces an `UNKNOWN_PROPERTY` diagnostic: +> +> ```ts +> engine.analyze("{{name.length}}", { +> type: "object", +> properties: { name: { type: "string" } }, +> }); +> // → valid: false, code: UNKNOWN_PROPERTY +> ``` + +--- + +## Conditional Schemas (`if`/`then`/`else`) + +JSON Schema `if`/`then`/`else` conditional schemas are **intentionally not supported**. This is a design decision — Typebars explicitly rejects schemas containing these keywords and reports an error. + +Use `oneOf`, `anyOf`, or `allOf` instead to express variant types. These combinators are fully supported by the resolver and the static analyzer. + +--- + +## What's Next? + +- **[Static Analysis](static-analysis.md)** — how validation and output inference use these schema features +- **[Templates](templates.md)** — object templates, block helpers, and how context switching works with schemas +- **[Advanced Features](advanced.md)** — `coerceSchema` for output type control +- **[API Reference](api-reference.md)** — full API documentation \ No newline at end of file diff --git a/docs/static-analysis.md b/docs/static-analysis.md new file mode 100644 index 0000000..65d3010 --- /dev/null +++ b/docs/static-analysis.md @@ -0,0 +1,496 @@ +# Static Analysis + +> **[← Back to README](../README.md)** | **Related:** [Schema Features](schema-features.md) · [Error Handling](error-handling.md) · [API Reference](api-reference.md) + +Typebars statically analyzes templates **before execution**. Given a template and a JSON Schema describing the available data, it: + +1. **Validates** every `{{expression}}` against the input schema +2. **Reports** structured diagnostics (errors and warnings) +3. **Infers** the JSON Schema of the output value + +No data is needed — the analysis is purely static. + +--- + +## Table of Contents + +- [Input Validation](#input-validation) + - [Property Validation](#property-validation) + - [Nested Properties (Dot Notation)](#nested-properties-dot-notation) + - [Validation Inside Block Helpers](#validation-inside-block-helpers) +- [Diagnostics](#diagnostics) + - [Diagnostic Structure](#diagnostic-structure) + - [Diagnostic Codes](#diagnostic-codes) +- [Output Schema Inference](#output-schema-inference) + - [Single Expression → Resolved Type](#single-expression--resolved-type) + - [Mixed Template → String](#mixed-template--string) + - [Single Block → Branch Type Inference](#single-block--branch-type-inference) + - [Object Templates → Object Schema](#object-templates--object-schema) + - [Literal Inputs → Primitive Schema](#literal-inputs--primitive-schema) + +--- + +## Input Validation + +### Property Validation + +Every `{{expression}}` in the template is validated against the input schema. If a property doesn't exist, Typebars reports an error with the available properties: + +```ts +const schema = { + type: "object", + properties: { + name: { type: "string" }, + age: { type: "number" }, + }, +}; + +// ✅ Valid — "name" exists in the schema +engine.analyze("{{name}}", schema); +// → { valid: true, diagnostics: [] } + +// ❌ Invalid — "firstName" does not exist +engine.analyze("{{firstName}}", schema); +// → { +// valid: false, +// diagnostics: [{ +// severity: "error", +// code: "UNKNOWN_PROPERTY", +// message: 'Property "firstName" does not exist in the context schema. Available properties: age, name', +// details: { path: "firstName", availableProperties: ["age", "name"] } +// }] +// } + +// Multiple errors are reported at once +engine.analyze("{{foo}} and {{bar}}", schema); +// → 2 diagnostics, one for "foo" and one for "bar" +``` + +### Nested Properties (Dot Notation) + +Dot notation is validated at every depth level: + +```ts +const schema = { + type: "object", + properties: { + address: { + type: "object", + properties: { + city: { type: "string" }, + zip: { type: "string" }, + }, + }, + metadata: { + type: "object", + properties: { + role: { type: "string", enum: ["admin", "user", "guest"] }, + }, + }, + }, +}; + +// ✅ Valid — full path resolved +engine.analyze("{{address.city}}", schema); // valid: true +engine.analyze("{{metadata.role}}", schema); // valid: true + +// ❌ Invalid — "country" doesn't exist inside "address" +engine.analyze("{{address.country}}", schema); +// → error: Property "address.country" does not exist +``` + +### Validation Inside Block Helpers + +The analyzer walks **into** block helpers and validates every expression in every branch. See [Block Helpers](templates.md#block-helpers) for the full list of supported blocks. + +```ts +const schema = { + type: "object", + properties: { + active: { type: "boolean" }, + name: { type: "string" }, + tags: { type: "array", items: { type: "string" } }, + orders: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "number" }, + product: { type: "string" }, + }, + }, + }, + address: { + type: "object", + properties: { + city: { type: "string" }, + }, + }, + }, +}; + +// ✅ #if — validates the condition AND both branches +engine.analyze("{{#if active}}{{name}}{{else}}unknown{{/if}}", schema); +// valid: true + +// ❌ #if — invalid properties inside branches are caught +engine.analyze("{{#if active}}{{badProp1}}{{else}}{{badProp2}}{{/if}}", schema); +// valid: false — 2 errors (one per branch) + +// ❌ #if — invalid condition is caught +engine.analyze("{{#if nonexistent}}yes{{/if}}", schema); +// valid: false — "nonexistent" doesn't exist + +// ✅ #each — validates that the target is an array, then validates +// the body against the item schema +engine.analyze("{{#each orders}}{{product}} #{{id}}{{/each}}", schema); +// valid: true — "product" and "id" exist in the item schema + +// ❌ #each — property doesn't exist in the item schema +engine.analyze("{{#each orders}}{{badField}}{{/each}}", schema); +// valid: false — "badField" doesn't exist in order items + +// ❌ #each — target is not an array +engine.analyze("{{#each name}}{{this}}{{/each}}", schema); +// valid: false — TYPE_MISMATCH: "{{#each}}" expects array, got "string" + +// ✅ #with — changes context to a sub-object, validates inner expressions +engine.analyze("{{#with address}}{{city}}{{/with}}", schema); +// valid: true + +// ❌ #with — property doesn't exist in the sub-context +engine.analyze("{{#with address}}{{country}}{{/with}}", schema); +// valid: false — "country" doesn't exist inside "address" + +// ✅ Nested blocks — validated at every level +engine.analyze( + "{{#with address}}{{city}}{{/with}} — {{#each tags}}{{this}}{{/each}}", + schema, +); +// valid: true +``` + +**Key insight:** `{{#each}}` changes the schema context to the array's `items` schema. Inside `{{#each orders}}`, the context becomes `{ type: "object", properties: { id, product } }`. Inside `{{#each tags}}`, the context becomes `{ type: "string" }` and `{{this}}` refers to each string element. + +`{{#with}}` changes the schema context to the resolved sub-object schema. Inside `{{#with address}}`, the context becomes the schema of `address`. + +Sub-expression conditions like `{{#if (gt age 18)}}` are also fully validated — see [Built-in Helpers — Static Analysis of Sub-Expressions](helpers.md#static-analysis-of-sub-expressions). + +--- + +## Diagnostics + +### Diagnostic Structure + +Every diagnostic is a structured object with machine-readable fields: + +```ts +interface TemplateDiagnostic { + severity: "error" | "warning"; + code: DiagnosticCode; + message: string; + loc?: { + start: { line: number; column: number }; + end: { line: number; column: number }; + }; + source?: string; + details?: { + path?: string; + helperName?: string; + expected?: string; + actual?: string; + availableProperties?: string[]; + identifier?: number; + }; +} +``` + +See [Error Handling](error-handling.md) for how diagnostics are surfaced via error classes (`TemplateAnalysisError`). + +### Diagnostic Codes + +| Code | Severity | Description | +|------|----------|-------------| +| `UNKNOWN_PROPERTY` | error | Property doesn't exist in the schema | +| `TYPE_MISMATCH` | error | Incompatible type (e.g. `{{#each}}` on a non-array) | +| `MISSING_ARGUMENT` | error | Block helper used without required argument | +| `UNKNOWN_HELPER` | warning | Unknown block helper | +| `UNANALYZABLE` | warning | Expression can't be statically analyzed | +| `MISSING_IDENTIFIER_SCHEMAS` | error | `{{key:N}}` used but no identifier schemas provided — see [Identifiers](identifiers.md) | +| `UNKNOWN_IDENTIFIER` | error | Identifier N not found in identifier schemas — see [Identifiers](identifiers.md) | +| `IDENTIFIER_PROPERTY_NOT_FOUND` | error | Property doesn't exist in identifier's schema — see [Identifiers](identifiers.md) | +| `PARSE_ERROR` | error | Invalid Handlebars syntax | +| `ROOT_PATH_TRAVERSAL` | error | `$root` used with path traversal (e.g. `$root.name`) — see [`$root` token](advanced.md#root-token) | + +--- + +## Output Schema Inference + +This is where Typebars shines. Given a template and an input schema, Typebars **infers the JSON Schema of the output value**. The inferred type depends on the template structure. + +### Single Expression → Resolved Type + +When the template is a single `{{expression}}` (with optional whitespace around it), the output schema is the resolved type from the input schema: + +```ts +const schema = { + type: "object", + properties: { + name: { type: "string" }, + age: { type: "number" }, + score: { type: "integer" }, + active: { type: "boolean" }, + address: { + type: "object", + properties: { + city: { type: "string" }, + zip: { type: "string" }, + }, + }, + tags: { + type: "array", + items: { type: "string" }, + }, + role: { type: "string", enum: ["admin", "user", "guest"] }, + }, +}; + +engine.analyze("{{name}}", schema).outputSchema; +// → { type: "string" } + +engine.analyze("{{age}}", schema).outputSchema; +// → { type: "number" } + +engine.analyze("{{score}}", schema).outputSchema; +// → { type: "integer" } + +engine.analyze("{{active}}", schema).outputSchema; +// → { type: "boolean" } + +engine.analyze("{{address}}", schema).outputSchema; +// → { type: "object", properties: { city: { type: "string" }, zip: { type: "string" } } } + +engine.analyze("{{tags}}", schema).outputSchema; +// → { type: "array", items: { type: "string" } } + +// Dot notation resolves to the leaf type +engine.analyze("{{address.city}}", schema).outputSchema; +// → { type: "string" } + +// Enums are preserved +engine.analyze("{{role}}", schema).outputSchema; +// → { type: "string", enum: ["admin", "user", "guest"] } + +// Whitespace around a single expression is ignored +engine.analyze(" {{age}} ", schema).outputSchema; +// → { type: "number" } +``` + +**This is the key mechanism**: the output schema is **derived from** the input schema by resolving the expression path. `{{age}}` in a schema where `age` is `{ type: "number" }` produces an output schema of `{ type: "number" }`. + +### Mixed Template → String + +When a template contains text **and** expressions, or multiple expressions, the output is always `{ type: "string" }` — because Handlebars concatenates everything into a string: + +```ts +engine.analyze("Hello {{name}}", schema).outputSchema; +// → { type: "string" } + +engine.analyze("{{name}} ({{age}})", schema).outputSchema; +// → { type: "string" } + +engine.analyze("Just plain text", schema).outputSchema; +// → { type: "string" } +``` + +### Single Block → Branch Type Inference + +When the template is a **single block** (optionally surrounded by whitespace), Typebars infers the type from the block's branches: + +```ts +// Both branches are numeric literals → output is number +engine.analyze("{{#if active}}10{{else}}20{{/if}}", schema).outputSchema; +// → { type: "number" } + +// Both branches are booleans → output is boolean +engine.analyze("{{#if active}}true{{else}}false{{/if}}", schema).outputSchema; +// → { type: "boolean" } + +// Both branches are single expressions of the same type → that type +engine.analyze( + "{{#if active}}{{name}}{{else}}{{address.city}}{{/if}}", + schema, +).outputSchema; +// → { type: "string" } + +// Branches with different types → oneOf union +engine.analyze( + "{{#if active}}{{age}}{{else}}{{score}}{{/if}}", + schema, +).outputSchema; +// → { oneOf: [{ type: "number" }, { type: "integer" }] } + +engine.analyze( + "{{#if active}}42{{else}}hello{{/if}}", + schema, +).outputSchema; +// → { oneOf: [{ type: "number" }, { type: "string" }] } + +// null in one branch → union with null +engine.analyze( + "{{#if active}}null{{else}}fallback{{/if}}", + schema, +).outputSchema; +// → { oneOf: [{ type: "null" }, { type: "string" }] } + +// #unless works the same way +engine.analyze( + "{{#unless active}}0{{else}}1{{/unless}}", + schema, +).outputSchema; +// → { type: "number" } + +// #with as single block → type of the inner body +engine.analyze("{{#with address}}{{city}}{{/with}}", schema).outputSchema; +// → { type: "string" } + +// #each always produces string (concatenation of iterations) +engine.analyze("{{#each tags}}{{this}}{{/each}}", schema).outputSchema; +// → { type: "string" } +``` + +**Inference logic per block type:** + +| Block | Output Schema | +|-------|---------------| +| `{{#if}}` with else | `oneOf(then_type, else_type)` (simplified if both are equal) | +| `{{#if}}` without else | Type of the then branch | +| `{{#unless}}` | Same as `{{#if}}` (inverted semantics, same type inference) | +| `{{#each}}` | Always `{ type: "string" }` (concatenation) | +| `{{#with}}` | Type of the inner body | + +### Object Templates → Object Schema + +When you pass an object as a template, each property is analyzed independently and the output schema is an object schema. See [Object Templates](templates.md#object-templates) for execution examples. + +```ts +const schema = { + type: "object", + properties: { + name: { type: "string" }, + age: { type: "number" }, + city: { type: "string" }, + }, +}; + +const analysis = engine.analyze( + { + userName: "Hello {{name}}!", // mixed → string + userAge: "{{age}}", // single expression → number + location: "{{city}}", // single expression → string + }, + schema, +); + +analysis.outputSchema; +// → { +// type: "object", +// properties: { +// userName: { type: "string" }, +// userAge: { type: "number" }, +// location: { type: "string" }, +// }, +// required: ["userName", "userAge", "location"], +// } +``` + +Nesting works recursively: + +```ts +engine.analyze( + { + user: { + name: "{{name}}", + age: "{{age}}", + }, + meta: { + active: "{{active}}", + }, + }, + schema, +).outputSchema; +// → { +// type: "object", +// properties: { +// user: { +// type: "object", +// properties: { +// name: { type: "string" }, +// age: { type: "number" }, +// }, +// required: ["name", "age"], +// }, +// meta: { +// type: "object", +// properties: { +// active: { type: "boolean" }, +// }, +// required: ["active"], +// }, +// }, +// required: ["user", "meta"], +// } +``` + +If **any** property in the object template is invalid, the entire object is marked as `valid: false` and all diagnostics are collected. + +### Literal Inputs → Primitive Schema + +Non-string values (`number`, `boolean`, `null`) are treated as passthrough literals. They are always valid (the input schema is ignored) and their output schema is inferred from the value: + +```ts +engine.analyze(42, schema).outputSchema; +// → { type: "integer" } + +engine.analyze(3.14, schema).outputSchema; +// → { type: "number" } + +engine.analyze(true, schema).outputSchema; +// → { type: "boolean" } + +engine.analyze(null, schema).outputSchema; +// → { type: "null" } +``` + +This is useful in [object templates](templates.md#object-templates) where some properties are fixed values: + +```ts +engine.analyze( + { + name: "{{name}}", // → string (from schema) + version: 42, // → integer (literal) + isPublic: true, // → boolean (literal) + deleted: null, // → null (literal) + }, + schema, +).outputSchema; +// → { +// type: "object", +// properties: { +// name: { type: "string" }, +// version: { type: "integer" }, +// isPublic: { type: "boolean" }, +// deleted: { type: "null" }, +// }, +// required: ["name", "version", "isPublic", "deleted"], +// } +``` + +--- + +## What's Next? + +- **[Schema Features](schema-features.md)** — `$ref` resolution, combinators, `additionalProperties` +- **[Templates](templates.md)** — object templates, array templates, and block helpers +- **[Error Handling](error-handling.md)** — error classes and how diagnostics are surfaced +- **[Advanced Features](advanced.md)** — `coerceSchema`, `excludeTemplateExpression`, `$root` token \ No newline at end of file diff --git a/docs/templates.md b/docs/templates.md new file mode 100644 index 0000000..4082ef1 --- /dev/null +++ b/docs/templates.md @@ -0,0 +1,366 @@ +# Templates + +> **[← Back to README](../README.md)** | **Related:** [Static Analysis](static-analysis.md) · [Execution](execution.md) · [Helpers](helpers.md) · [API Reference](api-reference.md) + +Typebars accepts more than just strings. The `TemplateInput` type is a recursive union that supports objects, arrays, and literal values alongside standard Handlebars template strings. + +--- + +## Table of Contents + +- [Object Templates](#object-templates) + - [Basic Usage](#basic-usage) + - [Nested Objects](#nested-objects) + - [Mixed Values](#mixed-values) + - [Validation](#validation) +- [Array Templates](#array-templates) + - [Basic Usage](#array-basic-usage) + - [Mixed Element Types](#mixed-element-types) +- [Block Helpers](#block-helpers) + - [`{{#if}}` / `{{#unless}}`](#if--unless) + - [`{{#each}}`](#each) + - [`{{#with}}`](#with) + - [Nested Blocks](#nested-blocks) + +--- + +## Object Templates + +Pass an object where each property is a `TemplateInput`. Every property is analyzed and executed independently. The output is an object with the same keys but resolved values. + +### Basic Usage + +```ts +const engine = new Typebars(); + +const data = { + name: "Alice", + age: 30, + active: true, + tags: ["ts", "js"], + address: { city: "Paris" }, +}; + +const result = engine.execute( + { + greeting: "Hello {{name}}!", + userAge: "{{age}}", + tags: "{{tags}}", + fixed: 42, + nested: { + city: "{{address.city}}", + }, + }, + data, +); +// → { +// greeting: "Hello Alice!", ← string (mixed template) +// userAge: 30, ← number (single expression — type preserved) +// tags: ["ts", "js"], ← array (single expression — type preserved) +// fixed: 42, ← number (literal passthrough) +// nested: { city: "Paris" }, ← nested object +// } +``` + +### Nested Objects + +Nesting works recursively — each level is processed independently: + +```ts +engine.execute( + { + user: { + name: "{{name}}", + age: "{{age}}", + }, + meta: { + active: "{{active}}", + }, + }, + data, +); +// → { +// user: { name: "Alice", age: 30 }, +// meta: { active: true }, +// } +``` + +### Mixed Values + +Object properties can be any `TemplateInput` — strings, numbers, booleans, `null`, nested objects, or arrays: + +```ts +engine.execute( + { + name: "{{name}}", // Handlebars template + version: 42, // literal number + isPublic: true, // literal boolean + deleted: null, // literal null + tags: ["{{name}}", 42], // array template (see below) + nested: { city: "{{address.city}}" }, + }, + data, +); +``` + +### Validation + +When analyzing an object template, all properties are validated. If **any** property is invalid, the entire object is marked as `valid: false` and all diagnostics are collected: + +```ts +const analysis = engine.analyze( + { + ok: "{{name}}", + bad: "{{nonexistent}}", + }, + schema, +); +// analysis.valid → false +// analysis.diagnostics → [{ code: "UNKNOWN_PROPERTY", ... "nonexistent" ... }] +``` + +The inferred [output schema](static-analysis.md#object-templates--object-schema) is an object schema with each property's resolved type: + +```ts +analysis.outputSchema; +// → { +// type: "object", +// properties: { +// ok: { type: "string" }, +// bad: { type: "string" }, ← still inferred even if invalid +// }, +// required: ["ok", "bad"], +// } +``` + +--- + +## Array Templates + +Pass an array where each element is a `TemplateInput`. Every element is analyzed and executed independently. The output is an array with the same length but resolved values. + +### Basic Usage {#array-basic-usage} + +```ts +const engine = new Typebars(); + +const result = engine.execute( + ["{{name}}", "{{age}}", 42, true], + { name: "Alice", age: 30 }, +); +// → ["Alice", 30, 42, true] +``` + +Each element follows the same type preservation rules as any other template input: +- `"{{name}}"` → `"Alice"` (single expression → raw string value) +- `"{{age}}"` → `30` (single expression → raw number value) +- `42` → `42` (literal passthrough) +- `true` → `true` (literal passthrough) + +### Mixed Element Types + +Array elements can be any `TemplateInput`, including nested objects and arrays: + +```ts +engine.execute( + [ + "Hello {{name}}!", + "{{age}}", + { city: "{{address.city}}" }, + [1, "{{active}}"], + ], + data, +); +// → [ +// "Hello Alice!", +// 30, +// { city: "Paris" }, +// [1, true], +// ] +``` + +Analysis infers an array output schema with `items` describing the element types: + +```ts +engine.analyze( + ["{{name}}", "{{age}}", 42], + schema, +).outputSchema; +// → { type: "array", items: { oneOf: [{ type: "string" }, { type: "number" }, { type: "integer" }] } } +``` + +Array templates also support all [advanced options](advanced.md) like `coerceSchema` (with `items` propagation) and `excludeTemplateExpression`. + +--- + +## Block Helpers + +Block helpers control flow within templates. The [static analyzer](static-analysis.md#validation-inside-block-helpers) validates every expression inside every branch, and the [output schema inference](static-analysis.md#single-block--branch-type-inference) accounts for branch types. + +### `{{#if}}` / `{{#unless}}` + +Conditional rendering. The analyzer validates the condition and both branches. + +The condition can be a simple property reference **or a sub-expression** using one of the [built-in logical helpers](helpers.md#logical--comparison-helpers): + +```ts +// Simple property condition +engine.execute("{{#if active}}Online{{else}}Offline{{/if}}", data); +// → "Online" + +engine.execute("{{#unless active}}No{{else}}Yes{{/unless}}", { active: false }); +// → "No" + +// Sub-expression condition (see "Built-in Helpers") +engine.execute( + "{{#if (gt age 18)}}Adult{{else}}Minor{{/if}}", + { age: 30 }, +); +// → "Adult" + +engine.execute( + '{{#if (eq role "admin")}}Full access{{else}}Limited{{/if}}', + { role: "admin" }, +); +// → "Full access" +``` + +> **Note:** Handlebars natively only supports simple property references as `{{#if}}` conditions (e.g. `{{#if active}}`). Sub-expression conditions like `{{#if (gt age 18)}}` are made possible by the logical helpers that Typebars pre-registers on every engine instance. See [Built-in Logical & Comparison Helpers](helpers.md#logical--comparison-helpers) for details. + +**Output schema inference:** + +When the template is a single block, Typebars infers the output type from the branches: + +```ts +// Both branches are numbers → output is number +engine.analyze("{{#if active}}10{{else}}20{{/if}}", schema).outputSchema; +// → { type: "number" } + +// Different types → oneOf union +engine.analyze("{{#if active}}42{{else}}hello{{/if}}", schema).outputSchema; +// → { oneOf: [{ type: "number" }, { type: "string" }] } +``` + +See [Branch Type Inference](static-analysis.md#single-block--branch-type-inference) for the full inference rules. + +### `{{#each}}` + +Iterates over arrays. The analyzer validates that the target is an array and switches the schema context to the array's `items` schema: + +```ts +engine.execute("{{#each tags}}{{this}} {{/each}}", data); +// → "ts js " + +engine.execute("{{#each orders}}#{{id}} {{product}} {{/each}}", { + orders: [ + { id: 1, product: "Keyboard" }, + { id: 2, product: "Mouse" }, + ], +}); +// → "#1 Keyboard #2 Mouse " +``` + +**Context switching:** Inside `{{#each orders}}`, the context becomes the item schema. `{{id}}` and `{{product}}` are resolved from the item, not the root. + +Inside `{{#each tags}}` (where tags is `string[]`), the context becomes `{ type: "string" }` and `{{this}}` refers to each string element. + +**Nested `{{#each}}`:** + +```ts +engine.execute( + "{{#each groups}}[{{#each members}}{{this}}{{/each}}]{{/each}}", + { groups: [{ members: ["a", "b"] }, { members: ["c"] }] }, +); +// → "[ab][c]" +``` + +**Static analysis:** + +```ts +// ✅ Valid — "product" and "id" exist in the item schema +engine.analyze("{{#each orders}}{{product}} #{{id}}{{/each}}", schema); + +// ❌ Property doesn't exist in the item schema +engine.analyze("{{#each orders}}{{badField}}{{/each}}", schema); +// → UNKNOWN_PROPERTY + +// ❌ Target is not an array +engine.analyze("{{#each name}}{{this}}{{/each}}", schema); +// → TYPE_MISMATCH: "{{#each}}" expects array, got "string" +``` + +> **Output type:** `{{#each}}` always produces `{ type: "string" }` as its output schema, because the iteration results are concatenated into a single string by Handlebars. + +### `{{#with}}` + +Changes the context to a sub-object. The analyzer switches the schema context accordingly: + +```ts +engine.execute("{{#with address}}{{city}}, {{zip}}{{/with}}", { + address: { city: "Paris", zip: "75001" }, +}); +// → "Paris, 75001" +``` + +**Nested `{{#with}}`:** + +```ts +engine.analyze( + "{{#with level1}}{{#with level2}}{{value}}{{/with}}{{/with}}", + { + type: "object", + properties: { + level1: { + type: "object", + properties: { + level2: { + type: "object", + properties: { value: { type: "string" } }, + }, + }, + }, + }, + }, +); +// → valid: true +``` + +**Static analysis:** + +```ts +// ✅ Valid — "city" exists inside "address" +engine.analyze("{{#with address}}{{city}}{{/with}}", schema); + +// ❌ "country" doesn't exist in the sub-context +engine.analyze("{{#with address}}{{country}}{{/with}}", schema); +// → UNKNOWN_PROPERTY +``` + +> **Output type:** `{{#with}}` as a single block infers the type of its inner body. For example, `{{#with address}}{{city}}{{/with}}` infers `{ type: "string" }`. + +### Nested Blocks + +Blocks can be combined and nested. The analyzer validates at every level: + +```ts +engine.analyze( + "{{#with address}}{{city}}{{/with}} — {{#each tags}}{{this}}{{/each}}", + schema, +); +// → valid: true (both blocks are validated independently) + +engine.analyze( + "{{#if active}}{{#each orders}}{{product}}{{/each}}{{else}}none{{/if}}", + schema, +); +// → valid: true (nested #each inside #if is validated with the correct context) +``` + +--- + +## What's Next? + +- **[Built-in & Custom Helpers](helpers.md)** — math, logical, comparison, `map`, and custom helpers for use inside templates +- **[Static Analysis](static-analysis.md)** — how templates are validated and output types are inferred +- **[Execution](execution.md)** — type preservation, execution modes, and compiled templates +- **[Advanced Features](advanced.md)** — `coerceSchema`, `excludeTemplateExpression`, `$root` token \ No newline at end of file