API Reference
API Reference
Section titled “API Reference”This page provides complete API documentation for the YAPL TypeScript library, including all classes, interfaces, and configuration options.
Classes
Section titled “Classes”Base YAPL class for browser environments or when file system access is not needed.
import { YAPL } from "@yapl-language/yapl.ts";
const yapl = new YAPL(options);
Constructor
Section titled “Constructor”constructor(options: YAPLOptions)
Methods
Section titled “Methods”renderString()
Section titled “renderString()”Render a template string with variables.
async renderString( templateSource: string, vars?: Record<string, unknown>, currentDir?: string): Promise<Prompt>
Parameters:
templateSource
- The YAPL template as a stringvars
- Variables to pass to the template (optional)currentDir
- Directory to use for resolving relative includes (optional)
Returns: Promise resolving to a Prompt
object
Example:
const result = await yapl.renderString( 'Hello, {{ name | default("World") }}!', { name: "Alice" });console.log(result.content); // "Hello, Alice!"
setBaseDir()
Section titled “setBaseDir()”Update the base directory for template resolution.
setBaseDir(dir: string): void
Parameters:
dir
- New base directory path
render()
Section titled “render()”Render a template with variables. In browser environments, this requires loadFile
and resolvePath
options to be provided.
async render(templatePath: string, vars?: Record<string, unknown>): Promise<Prompt>
Parameters:
templatePath
- Path to template file or referencevars
- Variables to pass to the template (optional)
Returns: Promise resolving to a Prompt
object
Example:
// In browser with custom loadersconst yapl = new YAPL({ baseDir: "/templates", loadFile: async (path) => { const response = await fetch(path); return response.text(); }, resolvePath: (templateRef, fromDir, ensureExt) => { return new URL(ensureExt(templateRef), fromDir).href; },});
const result = await yapl.render("template.yapl", { name: "World" });
NodeYAPL
Section titled “NodeYAPL”Extended YAPL class with file system support for Node.js environments.
import { NodeYAPL } from "@yapl-language/yapl.ts";
const yapl = new NodeYAPL(options);
Constructor
Section titled “Constructor”constructor(options: YAPLOptions)
Methods
Section titled “Methods”Inherits all methods from YAPL
, plus:
render()
Section titled “render()”Render a template file with variables.
async render(templatePath: string, vars?: Record<string, unknown>): Promise<Prompt>
Parameters:
templatePath
- Path to template file (relative to baseDir)vars
- Variables to pass to the template (optional)
Returns: Promise resolving to a Prompt
object
Example:
const result = await yapl.render("agents/coder.md.yapl", { language: "TypeScript", experience: "expert",});
Interfaces
Section titled “Interfaces”YAPLOptions
Section titled “YAPLOptions”Configuration options for YAPL instances.
interface YAPLOptions { baseDir: string; cache?: boolean; strictPaths?: boolean; maxDepth?: number; whitespace?: WhitespaceOptions; resolvePath?: ( templateRef: string, fromDir: string, ensureExt: (p: string) => string ) => string; loadFile?: (absolutePath: string) => Promise<string>; ensureExtension?: (p: string) => string;}
Properties:
baseDir
Section titled “baseDir”- Type:
string
- Required: Yes
- Description: Base directory for template files
- Type:
boolean
- Default:
true
(Node.js only) - Description: Enable file caching (Node.js only)
strictPaths
Section titled “strictPaths”- Type:
boolean
- Default:
true
(Node.js only) - Description: Prevent path traversal outside baseDir (Node.js only)
maxDepth
Section titled “maxDepth”- Type:
number
- Default:
20
- Description: Maximum template nesting depth
whitespace
Section titled “whitespace”- Type:
WhitespaceOptions
- Description: Whitespace control configuration
resolvePath
Section titled “resolvePath”- Type:
function
- Description: Custom function to resolve template paths (browser environments)
loadFile
Section titled “loadFile”- Type:
function
- Description: Custom function to load template files (browser environments)
ensureExtension
Section titled “ensureExtension”- Type:
function
- Description: Custom function to ensure file extensions (browser environments)
WhitespaceOptions
Section titled “WhitespaceOptions”Configuration for whitespace handling.
interface WhitespaceOptions { trimBlocks?: boolean; lstripBlocks?: boolean; dedentBlocks?: boolean;}
Properties:
trimBlocks
Section titled “trimBlocks”- Type:
boolean
- Default:
true
- Description: Remove newlines after block tags (
{% %}
)
lstripBlocks
Section titled “lstripBlocks”- Type:
boolean
- Default:
true
- Description: Remove leading whitespace before block tags
dedentBlocks
Section titled “dedentBlocks”- Type:
boolean
- Default:
true
- Description: Remove common indentation from block content
Prompt
Section titled “Prompt”Result object returned by render methods.
interface Prompt { content: string; usedFiles: string[];}
Properties:
content
Section titled “content”- Type:
string
- Description: The rendered template content
usedFiles
Section titled “usedFiles”- Type:
string[]
- Description: Array of file paths used during rendering (includes, extends, mixins)
Type alias for template variables.
type Vars = Record<string, unknown>;
Variables can be any JSON-serializable values:
- Strings
- Numbers
- Booleans
- Objects
- Arrays
- null
Template Syntax
Section titled “Template Syntax”Variables
Section titled “Variables”{{ variable_name }}{{ variable_name | default("default value") }}{{ object.property }}{{ array.0 }}
Conditionals
Section titled “Conditionals”{% if condition %} Content when true{% else %} Content when false{% endif %}
{% if condition %} Content when true{% elseif other_condition %} Content when other condition is true{% else %} Content when all conditions are false{% endif %}
{% for item in array %} {{ item }}{% endfor %}
{% for item in [1, 2, 3] %} {{ item }}{% endfor %}
Template Inheritance
Section titled “Template Inheritance”{% extends "base_template.yapl" %}
{% block block_name %} Block content {{ super() }} {# Include parent block content #}{% endblock %}
Mixins
Section titled “Mixins”{% mixin "mixin_template.yapl" %}{% mixin "mixin1.yapl", "mixin2.yapl" %}
Includes
Section titled “Includes”{% include "included_template.yapl" %}{% include "template.yapl" with { "variable": "value" } %}
Comments
Section titled “Comments”{# This is a comment #}{#- This is a whitespace-trimmed comment -#}
Usage Examples
Section titled “Usage Examples”Basic Setup
Section titled “Basic Setup”import { NodeYAPL } from "@yapl-language/yapl.ts";
const yapl = new NodeYAPL({ baseDir: "./prompts", cache: true, strictPaths: true, maxDepth: 10, whitespace: { trimBlocks: true, lstripBlocks: true, dedentBlocks: true, },});
Rendering Templates
Section titled “Rendering Templates”// Render from fileconst fileResult = await yapl.render("agent.md.yapl", { name: "CodeBot", language: "Python",});
// Render from stringconst stringResult = await yapl.renderString( `Hello, {{ name }}!{% if role %}You are a {{ role }}.{% endif %}`, { name: "Assistant", role: "helper", });
console.log(fileResult.content);console.log(fileResult.usedFiles); // ['./prompts/agent.md.yapl', ...]
Error Handling
Section titled “Error Handling”try { const result = await yapl.render("nonexistent.yapl");} catch (error) { if (error.code === "ENOENT") { console.error("Template file not found"); } else if (error.message.includes("Max template depth exceeded")) { console.error("Template recursion detected"); } else if (error.message.includes("escapes baseDir")) { console.error("Path traversal attempt blocked"); } else { console.error("Template rendering error:", error.message); }}
Dynamic Configuration
Section titled “Dynamic Configuration”// Create with minimal configconst yapl = new NodeYAPL({ baseDir: "./prompts" });
// Update base directoryyapl.setBaseDir("./different-prompts");
// Render with custom whitespace for specific templateconst customRenderer = new NodeYAPL({ baseDir: "./prompts", whitespace: { trimBlocks: false, lstripBlocks: false, dedentBlocks: true, },});
Browser Usage
Section titled “Browser Usage”import { YAPL } from "@yapl-language/yapl.ts";
const yapl = new YAPL({ baseDir: "/virtual", resolvePath: (templateRef, fromDir, ensureExt) => { return new URL(ensureExt(templateRef), fromDir).href; }, loadFile: async (absolutePath) => { const response = await fetch(absolutePath); return response.text(); },});
// Render with custom loadersconst result = await yapl.render("template.yapl", variables);
Advanced Variable Handling
Section titled “Advanced Variable Handling”const complexVars = { user: { name: "Alice", profile: { email: "alice@example.com", preferences: { theme: "dark", notifications: true, }, }, roles: ["admin", "developer"], }, config: { debug: true, version: "1.2.3", }, features: ["feature1", "feature2"],};
const result = await yapl.renderString( `User: {{ user.name }}Email: {{ user.profile.email }}Theme: {{ user.profile.preferences.theme }}First role: {{ user.roles.0 }}Debug mode: {{ config.debug }}`, complexVars);
File Caching
Section titled “File Caching”// Enable caching (default)const cachedYapl = new NodeYAPL({ baseDir: "./prompts", cache: true,});
// Disable caching for developmentconst uncachedYapl = new NodeYAPL({ baseDir: "./prompts", cache: false,});
// First render loads from file systemawait cachedYapl.render("template.yapl");
// Second render uses cached contentawait cachedYapl.render("template.yapl"); // Faster!
Path Security
Section titled “Path Security”// Strict paths enabled (default)const secureYapl = new NodeYAPL({ baseDir: "./prompts", strictPaths: true,});
try { // This will throw an error await secureYapl.render("../../../etc/passwd");} catch (error) { console.error(error.message); // "Path escapes baseDir"}
// Disable for special use cases (not recommended)const unsecureYapl = new NodeYAPL({ baseDir: "./prompts", strictPaths: false,});
Type Definitions
Section titled “Type Definitions”For TypeScript users, all types are exported:
import { YAPL, NodeYAPL, YAPLOptions, WhitespaceOptions, Prompt, Vars,} from "@yapl-language/yapl.ts";
Error Types
Section titled “Error Types”Common errors you might encounter:
File System Errors
Section titled “File System Errors”ENOENT
- Template file not foundEACCES
- Permission deniedEISDIR
- Path is a directory, not a file
Template Errors
Section titled “Template Errors”Max template depth exceeded
- Circular dependency or too deep nestingPath escapes baseDir
- Attempted path traversal with strictPaths enabledNo resolvePath provided
- Missing path resolver in browser environmentNo loadFile provided
- Missing file loader in browser environment
Syntax Errors
Section titled “Syntax Errors”- Template parsing errors for malformed YAPL syntax
- Missing
{% endif %}
or{% endblock %}
tags - Invalid variable names or expressions