Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | 1x 1x 2x 2x 1x 2x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 30x 32x 32x 32x 30x 30x 7x 7x 7x 7x 7x 13x 13x 7x 7x 35x 35x 35x 35x 35x 35x 35x 35x 35x 3x 3x 2x 2x 4x 4x 4x 2x 2x 3x 35x 35x 35x 35x 6x 6x 6x 3x 3x 6x 35x 35x 35x 35x 11x 11x 14x 12x 14x 14x 11x 11x 11x 11x 35x 35x 35x 35x 12x 12x 12x 10x 12x 35x 35x 35x 1x 28x 28x 28x 26x 26x 28x 2x 2x 28x 7x 7x 28x 28x 1x 2x 2x 1x 1x 1x | /**
* AgentKits — Prompt Template Engine
*
* Lightweight template engine with variables, conditionals, loops, and helpers.
*
* Usage:
* import { createTemplate, render } from 'agentkits/prompt-template';
* const tmpl = createTemplate('Hello {{name}}!');
* const result = tmpl.render({ name: 'World' });
*/
// ── Types ──────────────────────────────────────────────────────────
export interface TemplateHelpers {
[name: string]: (...args: any[]) => string;
}
export interface Template {
render(context: Record<string, any>): string;
readonly source: string;
readonly variables: string[];
}
export interface TemplateEngineConfig {
helpers?: TemplateHelpers;
/** Custom delimiters [open, close]. Default: ['{{', '}}'] */
delimiters?: [string, string];
}
// ── Built-in Helpers ───────────────────────────────────────────────
const BUILTIN_HELPERS: TemplateHelpers = {
date(format?: string): string {
const d = new Date();
if (format === 'iso') return d.toISOString();
if (format === 'date') return d.toISOString().split('T')[0];
return d.toLocaleString();
},
truncate(str: string, len: number = 100): string {
if (typeof str !== 'string') return String(str);
return str.length > len ? str.slice(0, len) + '...' : str;
},
json(obj: any, indent?: number): string {
return JSON.stringify(obj, null, indent ?? 2);
},
uppercase(str: string): string {
return String(str).toUpperCase();
},
lowercase(str: string): string {
return String(str).toLowerCase();
},
length(arr: any[] | string): string {
return String(arr?.length ?? 0);
},
};
// ── Engine ─────────────────────────────────────────────────────────
function resolveValue(path: string, context: Record<string, any>): any {
const parts = path.trim().split('.');
let val: any = context;
for (const p of parts) {
if (val == null) return undefined;
val = val[p];
}
return val;
}
function extractVariables(source: string): string[] {
const vars = new Set<string>();
const re = /\{\{(?!#|\/)([\w.]+)\}\}/g;
let m;
while ((m = re.exec(source))) {
vars.add(m[1]);
}
return [...vars];
}
function renderTemplate(
source: string,
context: Record<string, any>,
helpers: TemplateHelpers,
): string {
let result = source;
// Process {{#each items}}...{{/each}}
result = result.replace(
/\{\{#each\s+([\w.]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,
(_, key, body) => {
const arr = resolveValue(key, context);
if (!Array.isArray(arr)) return '';
return arr
.map((item, index) => {
const itemCtx = { ...context, this: item, '@index': index, '@first': index === 0, '@last': index === arr.length - 1 };
if (typeof item === 'object' && item !== null) Object.assign(itemCtx, item);
return renderTemplate(body, itemCtx, helpers);
})
.join('');
},
);
// Process {{#if condition}}...{{else}}...{{/if}}
result = result.replace(
/\{\{#if\s+([\w.]+)\}\}([\s\S]*?)(?:\{\{else\}\}([\s\S]*?))?\{\{\/if\}\}/g,
(_, key, ifBody, elseBody) => {
const val = resolveValue(key, context);
const truthy = Array.isArray(val) ? val.length > 0 : Boolean(val);
return truthy
? renderTemplate(ifBody, context, helpers)
: (elseBody ? renderTemplate(elseBody, context, helpers) : '');
},
);
// Process {{helper arg1 arg2}} — simple helper calls
result = result.replace(
/\{\{(\w+)\s+([\s\S]*?)\}\}/g,
(match, name, argsStr) => {
if (helpers[name]) {
const args = argsStr.split(/\s+/).map((a: string) => {
if (a.startsWith('"') && a.endsWith('"')) return a.slice(1, -1);
const num = Number(a);
if (!isNaN(num)) return num;
return resolveValue(a, context) ?? a;
});
return helpers[name](...args);
}
// Not a helper, try as dotted variable
return match;
},
);
// Process simple {{variable}}
result = result.replace(
/\{\{([\w.]+)\}\}/g,
(_, key) => {
const val = resolveValue(key, context);
if (val === undefined || val === null) return '';
if (typeof val === 'object') return JSON.stringify(val);
return String(val);
},
);
return result;
}
// ── Public API ─────────────────────────────────────────────────────
export function createTemplate(source: string, config: TemplateEngineConfig = {}): Template {
const helpers = { ...BUILTIN_HELPERS, ...config.helpers };
return {
render(context) {
return renderTemplate(source, context, helpers);
},
get source() {
return source;
},
get variables() {
return extractVariables(source);
},
};
}
/** Convenience: render a template string directly */
export function render(source: string, context: Record<string, any>, config: TemplateEngineConfig = {}): string {
return createTemplate(source, config).render(context);
}
/** Register a global helper */
export function registerHelper(name: string, fn: (...args: any[]) => string): void {
BUILTIN_HELPERS[name] = fn;
}
|