typebars 1.1.1 → 1.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/analyzer.js +1 -1
- package/dist/cjs/analyzer.js.map +1 -1
- package/dist/cjs/executor.js +1 -1
- package/dist/cjs/executor.js.map +1 -1
- package/dist/cjs/helpers/array-helpers.d.ts +9 -0
- package/dist/cjs/helpers/array-helpers.js +2 -0
- package/dist/cjs/helpers/array-helpers.js.map +1 -0
- package/dist/cjs/helpers/index.d.ts +1 -0
- package/dist/cjs/helpers/index.js +1 -1
- package/dist/cjs/helpers/index.js.map +1 -1
- package/dist/cjs/parser.d.ts +8 -0
- package/dist/cjs/parser.js +1 -1
- package/dist/cjs/parser.js.map +1 -1
- package/dist/cjs/typebars.js +1 -1
- package/dist/cjs/typebars.js.map +1 -1
- package/dist/esm/analyzer.js +1 -1
- package/dist/esm/analyzer.js.map +1 -1
- package/dist/esm/executor.js +1 -1
- package/dist/esm/executor.js.map +1 -1
- package/dist/esm/helpers/array-helpers.d.ts +9 -0
- package/dist/esm/helpers/array-helpers.js +2 -0
- package/dist/esm/helpers/array-helpers.js.map +1 -0
- package/dist/esm/helpers/index.d.ts +1 -0
- package/dist/esm/helpers/index.js +1 -1
- package/dist/esm/helpers/index.js.map +1 -1
- package/dist/esm/parser.d.ts +8 -0
- package/dist/esm/parser.js +1 -1
- package/dist/esm/parser.js.map +1 -1
- package/dist/esm/typebars.js +1 -1
- package/dist/esm/typebars.js.map +1 -1
- package/package.json +1 -1
package/dist/esm/executor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/executor.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { dispatchExecute } from \"./dispatch.ts\";\nimport { TemplateRuntimeError } from \"./errors.ts\";\nimport { DefaultHelpers } from \"./helpers/default-helpers.ts\";\nimport { MapHelpers } from \"./helpers/map-helpers.ts\";\nimport {\n\tcanUseFastPath,\n\tcoerceLiteral,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectiveBody,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisRootPathTraversal,\n\tisRootSegments,\n\tisSingleExpression,\n\tisThisExpression,\n\tparse,\n\tROOT_TOKEN,\n} from \"./parser.ts\";\nimport type {\n\tHelperDefinition,\n\tIdentifierData,\n\tTemplateInput,\n} from \"./types.ts\";\nimport { LRUCache } from \"./utils.ts\";\n\n// ─── Template Executor ───────────────────────────────────────────────────────\n// Executes a Handlebars template with real data.\n//\n// Four execution modes (from fastest to most general):\n//\n// 1. **Single expression** (`{{value}}` or ` {{value}} `) → returns the raw\n// value without converting to string. This preserves the original type\n// (number, boolean, object, array, null).\n//\n// 2. **Fast-path** (text + simple expressions, no blocks or helpers) →\n// direct concatenation without going through Handlebars.compile(). Up to\n// 10-100x faster for simple templates like `Hello {{name}}`.\n//\n// 3. **Single block** (`{{#if x}}10{{else}}20{{/if}}` possibly surrounded\n// by whitespace) → rendered via Handlebars then intelligently coerced\n// (detecting number, boolean, null literals).\n//\n// 4. **Mixed template** (text + multiple blocks, helpers, …) →\n// delegates to Handlebars which always produces a string.\n//\n// ─── Caching ─────────────────────────────────────────────────────────────────\n// Handlebars-compiled templates are cached in an LRU cache to avoid costly\n// recompilation on repeated calls.\n//\n// Two cache levels:\n// - **Global cache** (module-level) for standalone `execute()` calls\n// - **Instance cache** for `Typebars` (passed via `ExecutorContext`)\n//\n// ─── Template Identifiers ────────────────────────────────────────────────────\n// The `{{key:N}}` syntax allows resolving a variable from a specific data\n// source, identified by an integer N. The optional `identifierData` parameter\n// provides a mapping `{ [id]: { key: value, ... } }`.\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Optional context for execution (used by Typebars/CompiledTemplate) */\nexport interface ExecutorContext {\n\t/**\n\t * Data by identifier `{ [id]: { key: value } }`.\n\t *\n\t * Each identifier can map to a single object (standard) or an array\n\t * of objects (aggregated multi-version data). When the value is an\n\t * array, `{{key:N}}` extracts the property from each element.\n\t */\n\tidentifierData?: IdentifierData;\n\t/** Pre-compiled Handlebars template (for CompiledTemplate) */\n\tcompiledTemplate?: HandlebarsTemplateDelegate;\n\t/** Isolated Handlebars environment (for custom helpers) */\n\thbs?: typeof Handlebars;\n\t/** Compilation cache shared by the engine */\n\tcompilationCache?: LRUCache<string, HandlebarsTemplateDelegate>;\n\t/**\n\t * Explicit coercion schema for the output value.\n\t * When set with a primitive type, the execution result will be coerced\n\t * to match the declared type instead of using auto-detection.\n\t */\n\tcoerceSchema?: JSONSchema7;\n\t/** Registered helpers (for direct execution of special helpers like `map`) */\n\thelpers?: Map<string, HelperDefinition>;\n}\n\n// ─── Global Compilation Cache ────────────────────────────────────────────────\n// Used by the standalone `execute()` function and `renderWithHandlebars()`.\n// `Typebars` instances use their own cache.\nconst globalCompilationCache = new LRUCache<string, HandlebarsTemplateDelegate>(\n\t128,\n);\n\n// ─── Public API (backward-compatible) ────────────────────────────────────────\n\n/**\n * Executes a template with the provided data and returns the result.\n *\n * The return type depends on the template structure:\n * - Single expression `{{expr}}` → raw value (any)\n * - Single block → coerced value (number, boolean, null, or string)\n * - Mixed template → `string`\n *\n * @param template - The template string\n * @param data - The main context data\n * @param identifierData - (optional) Data by identifier `{ [id]: { key: value } }`\n */\nexport function execute(\n\ttemplate: TemplateInput,\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n): unknown {\n\treturn dispatchExecute(\n\t\ttemplate,\n\t\tundefined,\n\t\t// String handler — parse and execute the AST\n\t\t(tpl) => {\n\t\t\tconst ast = parse(tpl);\n\t\t\treturn executeFromAst(ast, tpl, data, { identifierData });\n\t\t},\n\t\t// Recursive handler — re-enter execute() for child elements\n\t\t(child) => execute(child, data, identifierData),\n\t);\n}\n\n// ─── Internal API (for Typebars / CompiledTemplate) ──────────────────────\n\n/**\n * Executes a template from an already-parsed AST.\n *\n * This function is the core of execution. It is used by:\n * - `execute()` (backward-compatible wrapper)\n * - `CompiledTemplate.execute()` (with pre-parsed AST and cache)\n * - `Typebars.execute()` (with cache and helpers)\n *\n * @param ast - The already-parsed Handlebars AST\n * @param template - The template source (for Handlebars compilation if needed)\n * @param data - The main context data\n * @param ctx - Optional execution context\n */\nexport function executeFromAst(\n\tast: hbs.AST.Program,\n\ttemplate: string,\n\tdata: unknown,\n\tctx?: ExecutorContext,\n): unknown {\n\tconst identifierData = ctx?.identifierData;\n\n\t// ── Case 1: strict single expression `{{expr}}` ──────────────────────\n\t// Exclude helper calls (params > 0 or hash) because they must go\n\t// through Handlebars for correct execution.\n\tif (isSingleExpression(ast)) {\n\t\tconst stmt = ast.body[0] as hbs.AST.MustacheStatement;\n\t\tif (stmt.params.length === 0 && !stmt.hash) {\n\t\t\treturn resolveExpression(stmt.path, data, identifierData, ctx?.helpers);\n\t\t}\n\t}\n\n\t// ── Case 1b: single expression with surrounding whitespace ` {{expr}} `\n\tconst singleExpr = getEffectivelySingleExpression(ast);\n\tif (singleExpr && singleExpr.params.length === 0 && !singleExpr.hash) {\n\t\treturn resolveExpression(\n\t\t\tsingleExpr.path,\n\t\t\tdata,\n\t\t\tidentifierData,\n\t\t\tctx?.helpers,\n\t\t);\n\t}\n\n\t// ── Case 1c: single expression with helper (params > 0) ──────────────\n\t// E.g. `{{ divide accountIds.length 10 }}` or `{{ math a \"+\" b }}`\n\t// The helper returns a typed value but Handlebars converts it to a\n\t// string. We render via Handlebars then coerce the result to recover\n\t// the original type (number, boolean, null).\n\tif (singleExpr && (singleExpr.params.length > 0 || singleExpr.hash)) {\n\t\t// ── Special case: helpers that return non-primitive values ────────\n\t\t// Some helpers (e.g. `map`) return arrays or objects. Handlebars\n\t\t// would stringify these, so we resolve their arguments directly and\n\t\t// call the helper's fn to preserve the raw return value.\n\t\tconst directResult = tryDirectHelperExecution(singleExpr, data, ctx);\n\t\tif (directResult !== undefined) {\n\t\t\treturn directResult.value;\n\t\t}\n\n\t\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\t\tconst raw = renderWithHandlebars(template, merged, ctx);\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\t// ── Case 2: fast-path for simple templates (text + expressions) ──────\n\t// If the template only contains text and simple expressions (no blocks,\n\t// no helpers with parameters), we can do direct concatenation without\n\t// going through Handlebars.compile().\n\tif (canUseFastPath(ast) && ast.body.length > 1) {\n\t\treturn executeFastPath(ast, data, identifierData);\n\t}\n\n\t// ── Case 3: single block (possibly surrounded by whitespace) ─────────\n\t// For conditional blocks (#if/#unless), try to evaluate the condition\n\t// and execute the selected branch directly to preserve non-string types\n\t// (e.g. arrays from `map`). Falls back to Handlebars rendering.\n\tconst singleBlock = getEffectivelySingleBlock(ast);\n\tif (singleBlock) {\n\t\tconst directResult = tryDirectBlockExecution(singleBlock, data, ctx);\n\t\tif (directResult !== undefined) {\n\t\t\treturn directResult.value;\n\t\t}\n\n\t\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\t\tconst raw = renderWithHandlebars(template, merged, ctx);\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\t// ── Case 4: mixed template ───────────────────────────────────────────\n\t// For purely static templates (only ContentStatements), coerce the\n\t// result to match the coerceSchema type or auto-detect the literal type.\n\t// For truly mixed templates (text + blocks + expressions), return string.\n\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\tconst raw = renderWithHandlebars(template, merged, ctx);\n\n\tconst effective = getEffectiveBody(ast);\n\tconst allContent = effective.every((s) => s.type === \"ContentStatement\");\n\tif (allContent) {\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\treturn raw;\n}\n\n// ─── Value Coercion ──────────────────────────────────────────────────────────\n// Coerces a raw string from Handlebars rendering based on an optional\n// coerceSchema. When no schema is provided, falls back to auto-detection\n// via `coerceLiteral`.\n\n/**\n * Coerces a raw string value based on an optional coercion schema.\n *\n * - If `coerceSchema` declares a primitive type (`string`, `number`,\n * `integer`, `boolean`, `null`), the value is cast to that type.\n * - Otherwise, falls back to `coerceLiteral` (auto-detection).\n *\n * @param raw - The raw string from Handlebars rendering\n * @param coerceSchema - Optional schema declaring the desired output type\n * @returns The coerced value\n */\nfunction coerceValue(raw: string, coerceSchema?: JSONSchema7): unknown {\n\tif (coerceSchema) {\n\t\tconst targetType = coerceSchema.type;\n\t\tif (typeof targetType === \"string\") {\n\t\t\tif (targetType === \"string\") return raw;\n\t\t\tif (targetType === \"number\" || targetType === \"integer\") {\n\t\t\t\tconst trimmed = raw.trim();\n\t\t\t\tif (trimmed === \"\") return undefined;\n\t\t\t\tconst num = Number(trimmed);\n\t\t\t\tif (Number.isNaN(num)) return undefined;\n\t\t\t\tif (targetType === \"integer\" && !Number.isInteger(num))\n\t\t\t\t\treturn undefined;\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tif (targetType === \"boolean\") {\n\t\t\t\tconst lower = raw.trim().toLowerCase();\n\t\t\t\tif (lower === \"true\") return true;\n\t\t\t\tif (lower === \"false\") return false;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (targetType === \"null\") return null;\n\t\t}\n\t}\n\t// No coerceSchema or non-primitive type → auto-detect\n\treturn coerceLiteral(raw);\n}\n\n// ─── Fast-Path Execution ─────────────────────────────────────────────────────\n// For templates consisting only of text and simple expressions (no blocks,\n// no helpers), we bypass Handlebars and do direct concatenation.\n// This is significantly faster.\n\n/**\n * Executes a template via the fast-path (direct concatenation).\n *\n * Precondition: `canUseFastPath(ast)` must return `true`.\n *\n * @param ast - The template AST (only ContentStatement and simple MustacheStatement)\n * @param data - The context data\n * @param identifierData - Data by identifier (optional)\n * @returns The resulting string\n */\nfunction executeFastPath(\n\tast: hbs.AST.Program,\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n): string {\n\tlet result = \"\";\n\n\tfor (const stmt of ast.body) {\n\t\tif (stmt.type === \"ContentStatement\") {\n\t\t\tresult += (stmt as hbs.AST.ContentStatement).value;\n\t\t} else if (stmt.type === \"MustacheStatement\") {\n\t\t\tconst value = resolveExpression(\n\t\t\t\t(stmt as hbs.AST.MustacheStatement).path,\n\t\t\t\tdata,\n\t\t\t\tidentifierData,\n\t\t\t);\n\t\t\t// Handlebars converts values to strings for rendering.\n\t\t\t// We replicate this behavior: null/undefined → \"\", otherwise String(value).\n\t\t\tif (value != null) {\n\t\t\t\tresult += String(value);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n// ─── Direct Expression Resolution ────────────────────────────────────────────\n// Used for single-expression templates and the fast-path, to return the raw\n// value without going through the Handlebars engine.\n\n/**\n * Resolves an AST expression by following the path through the data.\n *\n * If the expression contains an identifier (e.g. `meetingId:1`), resolution\n * is performed in `identifierData[1]` instead of `data`.\n *\n * @param expr - The AST expression to resolve\n * @param data - The main data context\n * @param identifierData - Data by identifier (optional)\n * @returns The raw value pointed to by the expression\n */\nfunction resolveExpression(\n\texpr: hbs.AST.Expression,\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n\thelpers?: Map<string, HelperDefinition>,\n): unknown {\n\t// this / . → return the entire context\n\tif (isThisExpression(expr)) {\n\t\treturn data;\n\t}\n\n\t// Literals\n\tif (expr.type === \"StringLiteral\")\n\t\treturn (expr as hbs.AST.StringLiteral).value;\n\tif (expr.type === \"NumberLiteral\")\n\t\treturn (expr as hbs.AST.NumberLiteral).value;\n\tif (expr.type === \"BooleanLiteral\")\n\t\treturn (expr as hbs.AST.BooleanLiteral).value;\n\tif (expr.type === \"NullLiteral\") return null;\n\tif (expr.type === \"UndefinedLiteral\") return undefined;\n\n\t// ── SubExpression (nested helper call) ────────────────────────────────\n\t// E.g. `(map users 'cartItems')` used as an argument to another helper.\n\t// Resolve all arguments recursively and call the helper's fn directly.\n\tif (expr.type === \"SubExpression\") {\n\t\tconst subExpr = expr as hbs.AST.SubExpression;\n\t\tif (subExpr.path.type === \"PathExpression\") {\n\t\t\tconst helperName = (subExpr.path as hbs.AST.PathExpression).original;\n\t\t\tconst helper = helpers?.get(helperName);\n\t\t\tif (helper) {\n\t\t\t\tconst isMap = helperName === MapHelpers.MAP_HELPER_NAME;\n\t\t\t\tconst resolvedArgs: unknown[] = [];\n\t\t\t\tfor (let i = 0; i < subExpr.params.length; i++) {\n\t\t\t\t\tconst param = subExpr.params[i] as hbs.AST.Expression;\n\t\t\t\t\t// For `map`, the second argument is a property name literal\n\t\t\t\t\tif (isMap && i === 1 && param.type === \"StringLiteral\") {\n\t\t\t\t\t\tresolvedArgs.push((param as hbs.AST.StringLiteral).value);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolvedArgs.push(\n\t\t\t\t\t\t\tresolveExpression(param, data, identifierData, helpers),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn helper.fn(...resolvedArgs);\n\t\t\t}\n\t\t}\n\t\t// Unknown sub-expression helper — return undefined\n\t\treturn undefined;\n\t}\n\n\t// PathExpression — navigate through segments in the data object\n\tconst segments = extractPathSegments(expr);\n\tif (segments.length === 0) {\n\t\tthrow new TemplateRuntimeError(\n\t\t\t`Cannot resolve expression of type \"${expr.type}\"`,\n\t\t);\n\t}\n\n\t// Extract the potential identifier from the last segment BEFORE\n\t// checking for $root, so that both {{$root}} and {{$root:N}} are\n\t// handled uniformly.\n\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\n\n\t// $root path traversal ($root.name) — not supported, return undefined\n\t// (the analyzer already rejects it with a diagnostic).\n\tif (isRootPathTraversal(cleanSegments)) {\n\t\treturn undefined;\n\t}\n\n\t// $root → return the entire data context (or identifier data)\n\tif (isRootSegments(cleanSegments)) {\n\t\tif (identifier !== null && identifierData) {\n\t\t\tconst source = identifierData[identifier];\n\t\t\treturn source ?? undefined;\n\t\t}\n\t\tif (identifier !== null) {\n\t\t\t// Template uses an identifier but no identifierData was provided\n\t\t\treturn undefined;\n\t\t}\n\t\treturn data;\n\t}\n\n\tif (identifier !== null && identifierData) {\n\t\tconst source = identifierData[identifier];\n\t\tif (source) {\n\t\t\t// ── Aggregated identifier (array of objects) ──────────────────\n\t\t\t// When the identifier maps to an array of objects (multi-version\n\t\t\t// data), extract the property from each element to produce a\n\t\t\t// result array. E.g. {{accountId:4}} on [{accountId:\"A\"},{accountId:\"B\"}]\n\t\t\t// → [\"A\", \"B\"]\n\t\t\tif (Array.isArray(source)) {\n\t\t\t\treturn source\n\t\t\t\t\t.map((item) => resolveDataPath(item, cleanSegments))\n\t\t\t\t\t.filter((v) => v !== undefined);\n\t\t\t}\n\t\t\treturn resolveDataPath(source, cleanSegments);\n\t\t}\n\t\t// Source does not exist → undefined (like a missing key)\n\t\treturn undefined;\n\t}\n\n\tif (identifier !== null && !identifierData) {\n\t\t// Template uses an identifier but no identifierData was provided\n\t\treturn undefined;\n\t}\n\n\treturn resolveDataPath(data, cleanSegments);\n}\n\n/**\n * Navigates through a data object by following a path of segments.\n *\n * @param data - The data object\n * @param segments - The path segments (e.g. `[\"user\", \"address\", \"city\"]`)\n * @returns The value at the end of the path, or `undefined` if an\n * intermediate segment is null/undefined\n */\nexport function resolveDataPath(data: unknown, segments: string[]): unknown {\n\tlet current: unknown = data;\n\n\tfor (const segment of segments) {\n\t\tif (current === null || current === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (typeof current !== \"object\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcurrent = (current as Record<string, unknown>)[segment];\n\t}\n\n\treturn current;\n}\n\n// ─── Data Merging ────────────────────────────────────────────────────────────\n// For Handlebars rendering (mixed templates / blocks), we cannot intercept\n// resolution on a per-expression basis. Instead, we merge identifier data\n// into the main object using the format `\"key:N\"`.\n//\n// Handlebars parses `{{meetingId:1}}` as a PathExpression with a single\n// segment `\"meetingId:1\"`, so it looks up the key `\"meetingId:1\"` in the\n// data object — which matches our flattened format exactly.\n\n/**\n * Merges the main data with identifier data.\n *\n * @param data - Main data\n * @param identifierData - Data by identifier\n * @returns A merged object where identifier data appears as `\"key:N\"` keys\n *\n * @example\n * ```\n * mergeDataWithIdentifiers(\n * { name: \"Alice\" },\n * { 1: { meetingId: \"val1\" }, 2: { meetingId: \"val2\" } }\n * )\n * // → { name: \"Alice\", \"meetingId:1\": \"val1\", \"meetingId:2\": \"val2\" }\n * ```\n */\nfunction mergeDataWithIdentifiers(\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n): Record<string, unknown> {\n\t// Always include $root so that Handlebars can resolve {{$root}} in\n\t// mixed templates and block helpers (where we delegate to Handlebars\n\t// instead of resolving expressions ourselves).\n\t// When data is a primitive (e.g. number passed with {{$root}}), we\n\t// wrap it into an object so Handlebars can still function.\n\tconst base: Record<string, unknown> =\n\t\tdata !== null && typeof data === \"object\" && !Array.isArray(data)\n\t\t\t? (data as Record<string, unknown>)\n\t\t\t: {};\n\tconst merged: Record<string, unknown> = { ...base, [ROOT_TOKEN]: data };\n\n\tif (!identifierData) return merged;\n\n\tfor (const [id, idData] of Object.entries(identifierData)) {\n\t\t// Add `$root:N` so Handlebars can resolve {{$root:N}} in mixed/block\n\t\t// templates (where we delegate to Handlebars instead of resolving\n\t\t// expressions ourselves). The value is the entire identifier data\n\t\t// object (or array for aggregated identifiers).\n\t\tmerged[`${ROOT_TOKEN}:${id}`] = idData;\n\n\t\t// ── Aggregated identifier (array of objects) ─────────────────\n\t\t// When the identifier data is an array (multi-version), we cannot\n\t\t// flatten individual properties into `\"key:N\"` keys because there\n\t\t// are multiple values per key. The array is only accessible via\n\t\t// `$root:N` (already set above). Handlebars helpers like `map`\n\t\t// can then consume it: `{{ map ($root:4) \"accountId\" }}`.\n\t\tif (Array.isArray(idData)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const [key, value] of Object.entries(idData)) {\n\t\t\tmerged[`${key}:${id}`] = value;\n\t\t}\n\t}\n\n\treturn merged;\n}\n\n// ─── Handlebars Rendering ────────────────────────────────────────────────────\n// For complex templates (blocks, helpers), we delegate to Handlebars.\n// Compilation is cached to avoid costly recompilations.\n\n/**\n * Compiles and executes a template via Handlebars.\n *\n * Uses a compilation cache (LRU) to avoid recompiling the same template\n * on repeated calls. The cache is either:\n * - The global cache (for the standalone `execute()` function)\n * - The instance cache provided via `ExecutorContext` (for `Typebars`)\n *\n * @param template - The template string\n * @param data - The context data\n * @param ctx - Optional execution context (cache, Handlebars env)\n * @returns Always a string\n */\nfunction renderWithHandlebars(\n\ttemplate: string,\n\tdata: Record<string, unknown>,\n\tctx?: ExecutorContext,\n): string {\n\ttry {\n\t\t// 1. Use the pre-compiled template if available (CompiledTemplate)\n\t\tif (ctx?.compiledTemplate) {\n\t\t\treturn ctx.compiledTemplate(data);\n\t\t}\n\n\t\t// 2. Look up in the cache (instance or global)\n\t\tconst cache = ctx?.compilationCache ?? globalCompilationCache;\n\t\tconst hbs = ctx?.hbs ?? Handlebars;\n\n\t\tlet compiled = cache.get(template);\n\t\tif (!compiled) {\n\t\t\tcompiled = hbs.compile(template, {\n\t\t\t\t// Disable HTML-escaping by default — this engine is not\n\t\t\t\t// HTML-specific, we want raw values.\n\t\t\t\tnoEscape: true,\n\t\t\t\t// Strict mode: throws if a path does not exist in the data.\n\t\t\t\tstrict: false,\n\t\t\t});\n\t\t\tcache.set(template, compiled);\n\t\t}\n\n\t\treturn compiled(data);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new TemplateRuntimeError(message);\n\t}\n}\n\n/**\n * Clears the global Handlebars compilation cache.\n * Useful for tests or to free memory.\n */\nexport function clearCompilationCache(): void {\n\tglobalCompilationCache.clear();\n}\n\n// ─── Direct Block Execution ──────────────────────────────────────────────────\n// For conditional blocks (#if/#unless), we can evaluate the condition directly\n// and execute the selected branch through the type-preserving execution paths.\n// This avoids Handlebars stringification when the branch contains helpers that\n// return non-primitive values (e.g. `map` returning arrays).\n\n/**\n * Attempts to execute a conditional block directly by evaluating its condition\n * and executing the selected branch through type-preserving paths.\n *\n * Only handles `#if` and `#unless` blocks. Returns `{ value }` if the branch\n * was executed directly, or `undefined` to fall back to Handlebars rendering.\n */\nfunction tryDirectBlockExecution(\n\tblock: hbs.AST.BlockStatement,\n\tdata: unknown,\n\tctx?: ExecutorContext,\n): { value: unknown } | undefined {\n\tif (block.path.type !== \"PathExpression\") return undefined;\n\tconst helperName = (block.path as hbs.AST.PathExpression).original;\n\n\t// Only handle built-in conditional blocks\n\tif (helperName !== \"if\" && helperName !== \"unless\") return undefined;\n\tif (block.params.length !== 1) return undefined;\n\n\t// Evaluate the condition\n\tconst condition = resolveExpression(\n\t\tblock.params[0] as hbs.AST.Expression,\n\t\tdata,\n\t\tctx?.identifierData,\n\t\tctx?.helpers,\n\t);\n\n\t// Handlebars truthiness: empty arrays are falsy\n\tlet isTruthy: boolean;\n\tif (Array.isArray(condition)) {\n\t\tisTruthy = condition.length > 0;\n\t} else {\n\t\tisTruthy = !!condition;\n\t}\n\tif (helperName === \"unless\") isTruthy = !isTruthy;\n\n\tconst branch = isTruthy ? block.program : block.inverse;\n\tif (!branch) {\n\t\t// No matching branch (e.g. falsy #if with no {{else}}) → empty string\n\t\treturn { value: \"\" };\n\t}\n\n\t// Try to execute the branch as a single expression (preserves types)\n\tconst singleExpr = getEffectivelySingleExpression(branch);\n\tif (singleExpr) {\n\t\tif (singleExpr.params.length === 0 && !singleExpr.hash) {\n\t\t\treturn {\n\t\t\t\tvalue: resolveExpression(\n\t\t\t\t\tsingleExpr.path,\n\t\t\t\t\tdata,\n\t\t\t\t\tctx?.identifierData,\n\t\t\t\t\tctx?.helpers,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\t// Single expression with helper (e.g. {{map users \"name\"}})\n\t\tif (singleExpr.params.length > 0 || singleExpr.hash) {\n\t\t\tconst directResult = tryDirectHelperExecution(singleExpr, data, ctx);\n\t\t\tif (directResult !== undefined) return directResult;\n\t\t}\n\t}\n\n\t// Try to execute the branch as a nested conditional block (recursive)\n\tconst nestedBlock = getEffectivelySingleBlock(branch);\n\tif (nestedBlock) {\n\t\treturn tryDirectBlockExecution(nestedBlock, data, ctx);\n\t}\n\n\t// Branch is too complex for direct execution → fall back\n\treturn undefined;\n}\n\n// ─── Direct Helper Execution ─────────────────────────────────────────────────\n// Some helpers (e.g. `map`) return non-primitive values (arrays, objects)\n// that Handlebars would stringify. For these helpers, we resolve their\n// arguments directly and call the helper's `fn` to preserve the raw value.\n\n/** Set of helper names that must be executed directly (bypass Handlebars) */\nconst DIRECT_EXECUTION_HELPERS = new Set<string>([\n\tDefaultHelpers.DEFAULT_HELPER_NAME,\n\tMapHelpers.MAP_HELPER_NAME,\n]);\n\n/**\n * Attempts to execute a helper directly (without Handlebars rendering).\n *\n * Returns `{ value }` if the helper was executed directly, or `undefined`\n * if the helper should go through the normal Handlebars rendering path.\n *\n * @param stmt - The MustacheStatement containing the helper call\n * @param data - The context data\n * @param ctx - Optional execution context (with helpers and identifierData)\n */\nfunction tryDirectHelperExecution(\n\tstmt: hbs.AST.MustacheStatement,\n\tdata: unknown,\n\tctx?: ExecutorContext,\n): { value: unknown } | undefined {\n\t// Get the helper name from the path\n\tif (stmt.path.type !== \"PathExpression\") return undefined;\n\tconst helperName = (stmt.path as hbs.AST.PathExpression).original;\n\n\t// Only intercept known direct-execution helpers\n\tif (!DIRECT_EXECUTION_HELPERS.has(helperName)) return undefined;\n\n\t// Look up the helper definition\n\tconst helper = ctx?.helpers?.get(helperName);\n\tif (!helper) return undefined;\n\n\t// Resolve each argument from the data context.\n\t// For the `map` helper, the resolution strategy is:\n\t// - Arg 0 (array): resolve as a data path (e.g. `users` → array)\n\t// - Arg 1 (property): must be a StringLiteral (e.g. `\"name\"`)\n\t// The analyzer enforces this — bare identifiers like `name` are\n\t// rejected at analysis time because Handlebars would resolve them\n\t// as a data path instead of a literal property name.\n\tconst isMap = helperName === MapHelpers.MAP_HELPER_NAME;\n\n\tconst resolvedArgs: unknown[] = [];\n\tfor (let i = 0; i < stmt.params.length; i++) {\n\t\tconst param = stmt.params[i] as hbs.AST.Expression;\n\n\t\t// For `map`, the second argument (index 1) is a property name —\n\t\t// it must be a StringLiteral (enforced by the analyzer).\n\t\tif (isMap && i === 1) {\n\t\t\tif (param.type === \"StringLiteral\") {\n\t\t\t\tresolvedArgs.push((param as hbs.AST.StringLiteral).value);\n\t\t\t} else {\n\t\t\t\t// Fallback: resolve normally (will likely be undefined at runtime)\n\t\t\t\tresolvedArgs.push(\n\t\t\t\t\tresolveExpression(param, data, ctx?.identifierData, ctx?.helpers),\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tresolvedArgs.push(\n\t\t\t\tresolveExpression(param, data, ctx?.identifierData, ctx?.helpers),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Call the helper's fn directly with the resolved arguments\n\tconst value = helper.fn(...resolvedArgs);\n\treturn { value };\n}\n"],"names":["Handlebars","dispatchExecute","TemplateRuntimeError","DefaultHelpers","MapHelpers","canUseFastPath","coerceLiteral","extractExpressionIdentifier","extractPathSegments","getEffectiveBody","getEffectivelySingleBlock","getEffectivelySingleExpression","isRootPathTraversal","isRootSegments","isSingleExpression","isThisExpression","parse","ROOT_TOKEN","LRUCache","globalCompilationCache","execute","template","data","identifierData","undefined","tpl","ast","executeFromAst","child","ctx","stmt","body","params","length","hash","resolveExpression","path","helpers","singleExpr","directResult","tryDirectHelperExecution","value","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","coerceValue","coerceSchema","executeFastPath","singleBlock","tryDirectBlockExecution","effective","allContent","every","s","type","targetType","trimmed","trim","num","Number","isNaN","isInteger","lower","toLowerCase","result","String","expr","subExpr","helperName","original","helper","get","isMap","MAP_HELPER_NAME","resolvedArgs","i","param","push","fn","segments","cleanSegments","identifier","source","Array","isArray","map","item","resolveDataPath","filter","v","current","segment","base","id","idData","Object","entries","key","compiledTemplate","cache","compilationCache","hbs","compiled","compile","noEscape","strict","set","error","message","Error","clearCompilationCache","clear","block","condition","isTruthy","branch","program","inverse","nestedBlock","DIRECT_EXECUTION_HELPERS","Set","DEFAULT_HELPER_NAME","has"],"mappings":"AAAA,OAAOA,eAAgB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C4C,EAAE,CAI5B,GAAIH,OAASG,IAAM,EAAG,CACrB,GAAIC,MAAMtB,IAAI,GAAK,gBAAiB,CACnCoB,aAAaG,IAAI,CAAC,AAACD,MAAgCpC,KAAK,CACzD,KAAO,CAENkC,aAAaG,IAAI,CAChB3C,kBAAkB0C,MAAOvD,KAAMO,KAAKN,eAAgBM,KAAKQ,SAE3D,CACD,KAAO,CACNsC,aAAaG,IAAI,CAChB3C,kBAAkB0C,MAAOvD,KAAMO,KAAKN,eAAgBM,KAAKQ,SAE3D,CACD,CAGA,MAAMI,MAAQ8B,OAAOQ,EAAE,IAAIJ,cAC3B,MAAO,CAAElC,KAAM,CAChB"}
|
|
1
|
+
{"version":3,"sources":["../../src/executor.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { dispatchExecute } from \"./dispatch.ts\";\nimport { TemplateRuntimeError } from \"./errors.ts\";\nimport { ArrayHelpers } from \"./helpers/array-helpers.ts\";\nimport { DefaultHelpers } from \"./helpers/default-helpers.ts\";\nimport { MapHelpers } from \"./helpers/map-helpers.ts\";\nimport {\n\tcanUseFastPath,\n\tcoerceLiteral,\n\textractExpressionIdentifier,\n\textractPathSegments,\n\tgetEffectiveBody,\n\tgetEffectivelySingleBlock,\n\tgetEffectivelySingleExpression,\n\tisRootPathTraversal,\n\tisRootSegments,\n\tisSingleExpression,\n\tisThisExpression,\n\tparse,\n\tROOT_TOKEN,\n} from \"./parser.ts\";\nimport type {\n\tHelperDefinition,\n\tIdentifierData,\n\tTemplateInput,\n} from \"./types.ts\";\nimport { LRUCache } from \"./utils.ts\";\n\n// ─── Template Executor ───────────────────────────────────────────────────────\n// Executes a Handlebars template with real data.\n//\n// Four execution modes (from fastest to most general):\n//\n// 1. **Single expression** (`{{value}}` or ` {{value}} `) → returns the raw\n// value without converting to string. This preserves the original type\n// (number, boolean, object, array, null).\n//\n// 2. **Fast-path** (text + simple expressions, no blocks or helpers) →\n// direct concatenation without going through Handlebars.compile(). Up to\n// 10-100x faster for simple templates like `Hello {{name}}`.\n//\n// 3. **Single block** (`{{#if x}}10{{else}}20{{/if}}` possibly surrounded\n// by whitespace) → rendered via Handlebars then intelligently coerced\n// (detecting number, boolean, null literals).\n//\n// 4. **Mixed template** (text + multiple blocks, helpers, …) →\n// delegates to Handlebars which always produces a string.\n//\n// ─── Caching ─────────────────────────────────────────────────────────────────\n// Handlebars-compiled templates are cached in an LRU cache to avoid costly\n// recompilation on repeated calls.\n//\n// Two cache levels:\n// - **Global cache** (module-level) for standalone `execute()` calls\n// - **Instance cache** for `Typebars` (passed via `ExecutorContext`)\n//\n// ─── Template Identifiers ────────────────────────────────────────────────────\n// The `{{key:N}}` syntax allows resolving a variable from a specific data\n// source, identified by an integer N. The optional `identifierData` parameter\n// provides a mapping `{ [id]: { key: value, ... } }`.\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Optional context for execution (used by Typebars/CompiledTemplate) */\nexport interface ExecutorContext {\n\t/**\n\t * Data by identifier `{ [id]: { key: value } }`.\n\t *\n\t * Each identifier can map to a single object (standard) or an array\n\t * of objects (aggregated multi-version data). When the value is an\n\t * array, `{{key:N}}` extracts the property from each element.\n\t */\n\tidentifierData?: IdentifierData;\n\t/** Pre-compiled Handlebars template (for CompiledTemplate) */\n\tcompiledTemplate?: HandlebarsTemplateDelegate;\n\t/** Isolated Handlebars environment (for custom helpers) */\n\thbs?: typeof Handlebars;\n\t/** Compilation cache shared by the engine */\n\tcompilationCache?: LRUCache<string, HandlebarsTemplateDelegate>;\n\t/**\n\t * Explicit coercion schema for the output value.\n\t * When set with a primitive type, the execution result will be coerced\n\t * to match the declared type instead of using auto-detection.\n\t */\n\tcoerceSchema?: JSONSchema7;\n\t/** Registered helpers (for direct execution of special helpers like `map`) */\n\thelpers?: Map<string, HelperDefinition>;\n}\n\n// ─── Global Compilation Cache ────────────────────────────────────────────────\n// Used by the standalone `execute()` function and `renderWithHandlebars()`.\n// `Typebars` instances use their own cache.\nconst globalCompilationCache = new LRUCache<string, HandlebarsTemplateDelegate>(\n\t128,\n);\n\n// ─── Public API (backward-compatible) ────────────────────────────────────────\n\n/**\n * Executes a template with the provided data and returns the result.\n *\n * The return type depends on the template structure:\n * - Single expression `{{expr}}` → raw value (any)\n * - Single block → coerced value (number, boolean, null, or string)\n * - Mixed template → `string`\n *\n * @param template - The template string\n * @param data - The main context data\n * @param identifierData - (optional) Data by identifier `{ [id]: { key: value } }`\n */\nexport function execute(\n\ttemplate: TemplateInput,\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n): unknown {\n\treturn dispatchExecute(\n\t\ttemplate,\n\t\tundefined,\n\t\t// String handler — parse and execute the AST\n\t\t(tpl) => {\n\t\t\tconst ast = parse(tpl);\n\t\t\treturn executeFromAst(ast, tpl, data, { identifierData });\n\t\t},\n\t\t// Recursive handler — re-enter execute() for child elements\n\t\t(child) => execute(child, data, identifierData),\n\t);\n}\n\n// ─── Internal API (for Typebars / CompiledTemplate) ──────────────────────\n\n/**\n * Executes a template from an already-parsed AST.\n *\n * This function is the core of execution. It is used by:\n * - `execute()` (backward-compatible wrapper)\n * - `CompiledTemplate.execute()` (with pre-parsed AST and cache)\n * - `Typebars.execute()` (with cache and helpers)\n *\n * @param ast - The already-parsed Handlebars AST\n * @param template - The template source (for Handlebars compilation if needed)\n * @param data - The main context data\n * @param ctx - Optional execution context\n */\nexport function executeFromAst(\n\tast: hbs.AST.Program,\n\ttemplate: string,\n\tdata: unknown,\n\tctx?: ExecutorContext,\n): unknown {\n\tconst identifierData = ctx?.identifierData;\n\n\t// ── Case 1: strict single expression `{{expr}}` ──────────────────────\n\t// Exclude helper calls (params > 0 or hash) because they must go\n\t// through Handlebars for correct execution.\n\tif (isSingleExpression(ast)) {\n\t\tconst stmt = ast.body[0] as hbs.AST.MustacheStatement;\n\t\tif (stmt.params.length === 0 && !stmt.hash) {\n\t\t\treturn resolveExpression(stmt.path, data, identifierData, ctx?.helpers);\n\t\t}\n\t}\n\n\t// ── Case 1b: single expression with surrounding whitespace ` {{expr}} `\n\tconst singleExpr = getEffectivelySingleExpression(ast);\n\tif (singleExpr && singleExpr.params.length === 0 && !singleExpr.hash) {\n\t\treturn resolveExpression(\n\t\t\tsingleExpr.path,\n\t\t\tdata,\n\t\t\tidentifierData,\n\t\t\tctx?.helpers,\n\t\t);\n\t}\n\n\t// ── Case 1c: single expression with helper (params > 0) ──────────────\n\t// E.g. `{{ divide accountIds.length 10 }}` or `{{ math a \"+\" b }}`\n\t// The helper returns a typed value but Handlebars converts it to a\n\t// string. We render via Handlebars then coerce the result to recover\n\t// the original type (number, boolean, null).\n\tif (singleExpr && (singleExpr.params.length > 0 || singleExpr.hash)) {\n\t\t// ── Special case: helpers that return non-primitive values ────────\n\t\t// Some helpers (e.g. `map`) return arrays or objects. Handlebars\n\t\t// would stringify these, so we resolve their arguments directly and\n\t\t// call the helper's fn to preserve the raw return value.\n\t\tconst directResult = tryDirectHelperExecution(singleExpr, data, ctx);\n\t\tif (directResult !== undefined) {\n\t\t\treturn directResult.value;\n\t\t}\n\n\t\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\t\tconst raw = renderWithHandlebars(template, merged, ctx);\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\t// ── Case 2: fast-path for simple templates (text + expressions) ──────\n\t// If the template only contains text and simple expressions (no blocks,\n\t// no helpers with parameters), we can do direct concatenation without\n\t// going through Handlebars.compile().\n\tif (canUseFastPath(ast) && ast.body.length > 1) {\n\t\treturn executeFastPath(ast, data, identifierData);\n\t}\n\n\t// ── Case 3: single block (possibly surrounded by whitespace) ─────────\n\t// For conditional blocks (#if/#unless), try to evaluate the condition\n\t// and execute the selected branch directly to preserve non-string types\n\t// (e.g. arrays from `map`). Falls back to Handlebars rendering.\n\tconst singleBlock = getEffectivelySingleBlock(ast);\n\tif (singleBlock) {\n\t\tconst directResult = tryDirectBlockExecution(singleBlock, data, ctx);\n\t\tif (directResult !== undefined) {\n\t\t\treturn directResult.value;\n\t\t}\n\n\t\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\t\tconst raw = renderWithHandlebars(template, merged, ctx);\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\t// ── Case 4: mixed template ───────────────────────────────────────────\n\t// For purely static templates (only ContentStatements), coerce the\n\t// result to match the coerceSchema type or auto-detect the literal type.\n\t// For truly mixed templates (text + blocks + expressions), return string.\n\tconst merged = mergeDataWithIdentifiers(data, identifierData);\n\tconst raw = renderWithHandlebars(template, merged, ctx);\n\n\tconst effective = getEffectiveBody(ast);\n\tconst allContent = effective.every((s) => s.type === \"ContentStatement\");\n\tif (allContent) {\n\t\treturn coerceValue(raw, ctx?.coerceSchema);\n\t}\n\n\treturn raw;\n}\n\n// ─── Value Coercion ──────────────────────────────────────────────────────────\n// Coerces a raw string from Handlebars rendering based on an optional\n// coerceSchema. When no schema is provided, falls back to auto-detection\n// via `coerceLiteral`.\n\n/**\n * Coerces a raw string value based on an optional coercion schema.\n *\n * - If `coerceSchema` declares a primitive type (`string`, `number`,\n * `integer`, `boolean`, `null`), the value is cast to that type.\n * - Otherwise, falls back to `coerceLiteral` (auto-detection).\n *\n * @param raw - The raw string from Handlebars rendering\n * @param coerceSchema - Optional schema declaring the desired output type\n * @returns The coerced value\n */\nfunction coerceValue(raw: string, coerceSchema?: JSONSchema7): unknown {\n\tif (coerceSchema) {\n\t\tconst targetType = coerceSchema.type;\n\t\tif (typeof targetType === \"string\") {\n\t\t\tif (targetType === \"string\") return raw;\n\t\t\tif (targetType === \"number\" || targetType === \"integer\") {\n\t\t\t\tconst trimmed = raw.trim();\n\t\t\t\tif (trimmed === \"\") return undefined;\n\t\t\t\tconst num = Number(trimmed);\n\t\t\t\tif (Number.isNaN(num)) return undefined;\n\t\t\t\tif (targetType === \"integer\" && !Number.isInteger(num))\n\t\t\t\t\treturn undefined;\n\t\t\t\treturn num;\n\t\t\t}\n\t\t\tif (targetType === \"boolean\") {\n\t\t\t\tconst lower = raw.trim().toLowerCase();\n\t\t\t\tif (lower === \"true\") return true;\n\t\t\t\tif (lower === \"false\") return false;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (targetType === \"null\") return null;\n\t\t}\n\t}\n\t// No coerceSchema or non-primitive type → auto-detect\n\treturn coerceLiteral(raw);\n}\n\n// ─── Fast-Path Execution ─────────────────────────────────────────────────────\n// For templates consisting only of text and simple expressions (no blocks,\n// no helpers), we bypass Handlebars and do direct concatenation.\n// This is significantly faster.\n\n/**\n * Executes a template via the fast-path (direct concatenation).\n *\n * Precondition: `canUseFastPath(ast)` must return `true`.\n *\n * @param ast - The template AST (only ContentStatement and simple MustacheStatement)\n * @param data - The context data\n * @param identifierData - Data by identifier (optional)\n * @returns The resulting string\n */\nfunction executeFastPath(\n\tast: hbs.AST.Program,\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n): string {\n\tlet result = \"\";\n\n\tfor (const stmt of ast.body) {\n\t\tif (stmt.type === \"ContentStatement\") {\n\t\t\tresult += (stmt as hbs.AST.ContentStatement).value;\n\t\t} else if (stmt.type === \"MustacheStatement\") {\n\t\t\tconst value = resolveExpression(\n\t\t\t\t(stmt as hbs.AST.MustacheStatement).path,\n\t\t\t\tdata,\n\t\t\t\tidentifierData,\n\t\t\t);\n\t\t\t// Handlebars converts values to strings for rendering.\n\t\t\t// We replicate this behavior: null/undefined → \"\", otherwise String(value).\n\t\t\tif (value != null) {\n\t\t\t\tresult += String(value);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n// ─── Direct Expression Resolution ────────────────────────────────────────────\n// Used for single-expression templates and the fast-path, to return the raw\n// value without going through the Handlebars engine.\n\n/**\n * Resolves an AST expression by following the path through the data.\n *\n * If the expression contains an identifier (e.g. `meetingId:1`), resolution\n * is performed in `identifierData[1]` instead of `data`.\n *\n * @param expr - The AST expression to resolve\n * @param data - The main data context\n * @param identifierData - Data by identifier (optional)\n * @returns The raw value pointed to by the expression\n */\nfunction resolveExpression(\n\texpr: hbs.AST.Expression,\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n\thelpers?: Map<string, HelperDefinition>,\n): unknown {\n\t// this / . → return the entire context\n\tif (isThisExpression(expr)) {\n\t\treturn data;\n\t}\n\n\t// Literals\n\tif (expr.type === \"StringLiteral\")\n\t\treturn (expr as hbs.AST.StringLiteral).value;\n\tif (expr.type === \"NumberLiteral\")\n\t\treturn (expr as hbs.AST.NumberLiteral).value;\n\tif (expr.type === \"BooleanLiteral\")\n\t\treturn (expr as hbs.AST.BooleanLiteral).value;\n\tif (expr.type === \"NullLiteral\") return null;\n\tif (expr.type === \"UndefinedLiteral\") return undefined;\n\n\t// ── SubExpression (nested helper call) ────────────────────────────────\n\t// E.g. `(map users 'cartItems')` used as an argument to another helper.\n\t// Resolve all arguments recursively and call the helper's fn directly.\n\tif (expr.type === \"SubExpression\") {\n\t\tconst subExpr = expr as hbs.AST.SubExpression;\n\t\tif (subExpr.path.type === \"PathExpression\") {\n\t\t\tconst helperName = (subExpr.path as hbs.AST.PathExpression).original;\n\t\t\tconst helper = helpers?.get(helperName);\n\t\t\tif (helper) {\n\t\t\t\tconst isMap = helperName === MapHelpers.MAP_HELPER_NAME;\n\t\t\t\tconst resolvedArgs: unknown[] = [];\n\t\t\t\tfor (let i = 0; i < subExpr.params.length; i++) {\n\t\t\t\t\tconst param = subExpr.params[i] as hbs.AST.Expression;\n\t\t\t\t\t// For `map`, the second argument is a property name literal\n\t\t\t\t\tif (isMap && i === 1 && param.type === \"StringLiteral\") {\n\t\t\t\t\t\tresolvedArgs.push((param as hbs.AST.StringLiteral).value);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolvedArgs.push(\n\t\t\t\t\t\t\tresolveExpression(param, data, identifierData, helpers),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn helper.fn(...resolvedArgs);\n\t\t\t}\n\t\t}\n\t\t// Unknown sub-expression helper — return undefined\n\t\treturn undefined;\n\t}\n\n\t// PathExpression — navigate through segments in the data object\n\tconst segments = extractPathSegments(expr);\n\tif (segments.length === 0) {\n\t\tthrow new TemplateRuntimeError(\n\t\t\t`Cannot resolve expression of type \"${expr.type}\"`,\n\t\t);\n\t}\n\n\t// Extract the potential identifier from the last segment BEFORE\n\t// checking for $root, so that both {{$root}} and {{$root:N}} are\n\t// handled uniformly.\n\tconst { cleanSegments, identifier } = extractExpressionIdentifier(segments);\n\n\t// $root path traversal ($root.name) — not supported, return undefined\n\t// (the analyzer already rejects it with a diagnostic).\n\tif (isRootPathTraversal(cleanSegments)) {\n\t\treturn undefined;\n\t}\n\n\t// $root → return the entire data context (or identifier data)\n\tif (isRootSegments(cleanSegments)) {\n\t\tif (identifier !== null && identifierData) {\n\t\t\tconst source = identifierData[identifier];\n\t\t\treturn source ?? undefined;\n\t\t}\n\t\tif (identifier !== null) {\n\t\t\t// Template uses an identifier but no identifierData was provided\n\t\t\treturn undefined;\n\t\t}\n\t\treturn data;\n\t}\n\n\tif (identifier !== null && identifierData) {\n\t\tconst source = identifierData[identifier];\n\t\tif (source) {\n\t\t\t// ── Aggregated identifier (array of objects) ──────────────────\n\t\t\t// When the identifier maps to an array of objects (multi-version\n\t\t\t// data), extract the property from each element to produce a\n\t\t\t// result array. E.g. {{accountId:4}} on [{accountId:\"A\"},{accountId:\"B\"}]\n\t\t\t// → [\"A\", \"B\"]\n\t\t\tif (Array.isArray(source)) {\n\t\t\t\treturn source\n\t\t\t\t\t.map((item) => resolveDataPath(item, cleanSegments))\n\t\t\t\t\t.filter((v) => v !== undefined);\n\t\t\t}\n\t\t\treturn resolveDataPath(source, cleanSegments);\n\t\t}\n\t\t// Source does not exist → undefined (like a missing key)\n\t\treturn undefined;\n\t}\n\n\tif (identifier !== null && !identifierData) {\n\t\t// Template uses an identifier but no identifierData was provided\n\t\treturn undefined;\n\t}\n\n\treturn resolveDataPath(data, cleanSegments);\n}\n\n/**\n * Navigates through a data object by following a path of segments.\n *\n * @param data - The data object\n * @param segments - The path segments (e.g. `[\"user\", \"address\", \"city\"]`)\n * @returns The value at the end of the path, or `undefined` if an\n * intermediate segment is null/undefined\n */\nexport function resolveDataPath(data: unknown, segments: string[]): unknown {\n\tlet current: unknown = data;\n\n\tfor (const segment of segments) {\n\t\tif (current === null || current === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (typeof current !== \"object\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcurrent = (current as Record<string, unknown>)[segment];\n\t}\n\n\treturn current;\n}\n\n// ─── Data Merging ────────────────────────────────────────────────────────────\n// For Handlebars rendering (mixed templates / blocks), we cannot intercept\n// resolution on a per-expression basis. Instead, we merge identifier data\n// into the main object using the format `\"key:N\"`.\n//\n// Handlebars parses `{{meetingId:1}}` as a PathExpression with a single\n// segment `\"meetingId:1\"`, so it looks up the key `\"meetingId:1\"` in the\n// data object — which matches our flattened format exactly.\n\n/**\n * Merges the main data with identifier data.\n *\n * @param data - Main data\n * @param identifierData - Data by identifier\n * @returns A merged object where identifier data appears as `\"key:N\"` keys\n *\n * @example\n * ```\n * mergeDataWithIdentifiers(\n * { name: \"Alice\" },\n * { 1: { meetingId: \"val1\" }, 2: { meetingId: \"val2\" } }\n * )\n * // → { name: \"Alice\", \"meetingId:1\": \"val1\", \"meetingId:2\": \"val2\" }\n * ```\n */\nfunction mergeDataWithIdentifiers(\n\tdata: unknown,\n\tidentifierData?: IdentifierData,\n): Record<string, unknown> {\n\t// Always include $root so that Handlebars can resolve {{$root}} in\n\t// mixed templates and block helpers (where we delegate to Handlebars\n\t// instead of resolving expressions ourselves).\n\t// When data is a primitive (e.g. number passed with {{$root}}), we\n\t// wrap it into an object so Handlebars can still function.\n\tconst base: Record<string, unknown> =\n\t\tdata !== null && typeof data === \"object\" && !Array.isArray(data)\n\t\t\t? (data as Record<string, unknown>)\n\t\t\t: {};\n\tconst merged: Record<string, unknown> = { ...base, [ROOT_TOKEN]: data };\n\n\tif (!identifierData) return merged;\n\n\tfor (const [id, idData] of Object.entries(identifierData)) {\n\t\t// Add `$root:N` so Handlebars can resolve {{$root:N}} in mixed/block\n\t\t// templates (where we delegate to Handlebars instead of resolving\n\t\t// expressions ourselves). The value is the entire identifier data\n\t\t// object (or array for aggregated identifiers).\n\t\tmerged[`${ROOT_TOKEN}:${id}`] = idData;\n\n\t\t// ── Aggregated identifier (array of objects) ─────────────────\n\t\t// When the identifier data is an array (multi-version), we cannot\n\t\t// flatten individual properties into `\"key:N\"` keys because there\n\t\t// are multiple values per key. The array is only accessible via\n\t\t// `$root:N` (already set above). Handlebars helpers like `map`\n\t\t// can then consume it: `{{ map ($root:4) \"accountId\" }}`.\n\t\tif (Array.isArray(idData)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const [key, value] of Object.entries(idData)) {\n\t\t\tmerged[`${key}:${id}`] = value;\n\t\t}\n\t}\n\n\treturn merged;\n}\n\n// ─── Handlebars Rendering ────────────────────────────────────────────────────\n// For complex templates (blocks, helpers), we delegate to Handlebars.\n// Compilation is cached to avoid costly recompilations.\n\n/**\n * Compiles and executes a template via Handlebars.\n *\n * Uses a compilation cache (LRU) to avoid recompiling the same template\n * on repeated calls. The cache is either:\n * - The global cache (for the standalone `execute()` function)\n * - The instance cache provided via `ExecutorContext` (for `Typebars`)\n *\n * @param template - The template string\n * @param data - The context data\n * @param ctx - Optional execution context (cache, Handlebars env)\n * @returns Always a string\n */\nfunction renderWithHandlebars(\n\ttemplate: string,\n\tdata: Record<string, unknown>,\n\tctx?: ExecutorContext,\n): string {\n\ttry {\n\t\t// 1. Use the pre-compiled template if available (CompiledTemplate)\n\t\tif (ctx?.compiledTemplate) {\n\t\t\treturn ctx.compiledTemplate(data);\n\t\t}\n\n\t\t// 2. Look up in the cache (instance or global)\n\t\tconst cache = ctx?.compilationCache ?? globalCompilationCache;\n\t\tconst hbs = ctx?.hbs ?? Handlebars;\n\n\t\tlet compiled = cache.get(template);\n\t\tif (!compiled) {\n\t\t\tcompiled = hbs.compile(template, {\n\t\t\t\t// Disable HTML-escaping by default — this engine is not\n\t\t\t\t// HTML-specific, we want raw values.\n\t\t\t\tnoEscape: true,\n\t\t\t\t// Strict mode: throws if a path does not exist in the data.\n\t\t\t\tstrict: false,\n\t\t\t});\n\t\t\tcache.set(template, compiled);\n\t\t}\n\n\t\treturn compiled(data);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new TemplateRuntimeError(message);\n\t}\n}\n\n/**\n * Clears the global Handlebars compilation cache.\n * Useful for tests or to free memory.\n */\nexport function clearCompilationCache(): void {\n\tglobalCompilationCache.clear();\n}\n\n// ─── Direct Block Execution ──────────────────────────────────────────────────\n// For conditional blocks (#if/#unless), we can evaluate the condition directly\n// and execute the selected branch through the type-preserving execution paths.\n// This avoids Handlebars stringification when the branch contains helpers that\n// return non-primitive values (e.g. `map` returning arrays).\n\n/**\n * Attempts to execute a conditional block directly by evaluating its condition\n * and executing the selected branch through type-preserving paths.\n *\n * Only handles `#if` and `#unless` blocks. Returns `{ value }` if the branch\n * was executed directly, or `undefined` to fall back to Handlebars rendering.\n */\nfunction tryDirectBlockExecution(\n\tblock: hbs.AST.BlockStatement,\n\tdata: unknown,\n\tctx?: ExecutorContext,\n): { value: unknown } | undefined {\n\tif (block.path.type !== \"PathExpression\") return undefined;\n\tconst helperName = (block.path as hbs.AST.PathExpression).original;\n\n\t// Only handle built-in conditional blocks\n\tif (helperName !== \"if\" && helperName !== \"unless\") return undefined;\n\tif (block.params.length !== 1) return undefined;\n\n\t// Evaluate the condition\n\tconst condition = resolveExpression(\n\t\tblock.params[0] as hbs.AST.Expression,\n\t\tdata,\n\t\tctx?.identifierData,\n\t\tctx?.helpers,\n\t);\n\n\t// Handlebars truthiness: empty arrays are falsy\n\tlet isTruthy: boolean;\n\tif (Array.isArray(condition)) {\n\t\tisTruthy = condition.length > 0;\n\t} else {\n\t\tisTruthy = !!condition;\n\t}\n\tif (helperName === \"unless\") isTruthy = !isTruthy;\n\n\tconst branch = isTruthy ? block.program : block.inverse;\n\tif (!branch) {\n\t\t// No matching branch (e.g. falsy #if with no {{else}}) → empty string\n\t\treturn { value: \"\" };\n\t}\n\n\t// Try to execute the branch as a single expression (preserves types)\n\tconst singleExpr = getEffectivelySingleExpression(branch);\n\tif (singleExpr) {\n\t\tif (singleExpr.params.length === 0 && !singleExpr.hash) {\n\t\t\treturn {\n\t\t\t\tvalue: resolveExpression(\n\t\t\t\t\tsingleExpr.path,\n\t\t\t\t\tdata,\n\t\t\t\t\tctx?.identifierData,\n\t\t\t\t\tctx?.helpers,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\t// Single expression with helper (e.g. {{map users \"name\"}})\n\t\tif (singleExpr.params.length > 0 || singleExpr.hash) {\n\t\t\tconst directResult = tryDirectHelperExecution(singleExpr, data, ctx);\n\t\t\tif (directResult !== undefined) return directResult;\n\t\t}\n\t}\n\n\t// Try to execute the branch as a nested conditional block (recursive)\n\tconst nestedBlock = getEffectivelySingleBlock(branch);\n\tif (nestedBlock) {\n\t\treturn tryDirectBlockExecution(nestedBlock, data, ctx);\n\t}\n\n\t// Branch is too complex for direct execution → fall back\n\treturn undefined;\n}\n\n// ─── Direct Helper Execution ─────────────────────────────────────────────────\n// Some helpers (e.g. `map`) return non-primitive values (arrays, objects)\n// that Handlebars would stringify. For these helpers, we resolve their\n// arguments directly and call the helper's `fn` to preserve the raw value.\n\n/** Set of helper names that must be executed directly (bypass Handlebars) */\nconst DIRECT_EXECUTION_HELPERS = new Set<string>([\n\tArrayHelpers.ARRAY_HELPER_NAME,\n\tDefaultHelpers.DEFAULT_HELPER_NAME,\n\tMapHelpers.MAP_HELPER_NAME,\n]);\n\n/**\n * Attempts to execute a helper directly (without Handlebars rendering).\n *\n * Returns `{ value }` if the helper was executed directly, or `undefined`\n * if the helper should go through the normal Handlebars rendering path.\n *\n * @param stmt - The MustacheStatement containing the helper call\n * @param data - The context data\n * @param ctx - Optional execution context (with helpers and identifierData)\n */\nfunction tryDirectHelperExecution(\n\tstmt: hbs.AST.MustacheStatement,\n\tdata: unknown,\n\tctx?: ExecutorContext,\n): { value: unknown } | undefined {\n\t// Get the helper name from the path\n\tif (stmt.path.type !== \"PathExpression\") return undefined;\n\tconst helperName = (stmt.path as hbs.AST.PathExpression).original;\n\n\t// Only intercept known direct-execution helpers\n\tif (!DIRECT_EXECUTION_HELPERS.has(helperName)) return undefined;\n\n\t// Look up the helper definition\n\tconst helper = ctx?.helpers?.get(helperName);\n\tif (!helper) return undefined;\n\n\t// Resolve each argument from the data context.\n\t// For the `map` helper, the resolution strategy is:\n\t// - Arg 0 (array): resolve as a data path (e.g. `users` → array)\n\t// - Arg 1 (property): must be a StringLiteral (e.g. `\"name\"`)\n\t// The analyzer enforces this — bare identifiers like `name` are\n\t// rejected at analysis time because Handlebars would resolve them\n\t// as a data path instead of a literal property name.\n\tconst isMap = helperName === MapHelpers.MAP_HELPER_NAME;\n\n\tconst resolvedArgs: unknown[] = [];\n\tfor (let i = 0; i < stmt.params.length; i++) {\n\t\tconst param = stmt.params[i] as hbs.AST.Expression;\n\n\t\t// For `map`, the second argument (index 1) is a property name —\n\t\t// it must be a StringLiteral (enforced by the analyzer).\n\t\tif (isMap && i === 1) {\n\t\t\tif (param.type === \"StringLiteral\") {\n\t\t\t\tresolvedArgs.push((param as hbs.AST.StringLiteral).value);\n\t\t\t} else {\n\t\t\t\t// Fallback: resolve normally (will likely be undefined at runtime)\n\t\t\t\tresolvedArgs.push(\n\t\t\t\t\tresolveExpression(param, data, ctx?.identifierData, ctx?.helpers),\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tresolvedArgs.push(\n\t\t\t\tresolveExpression(param, data, ctx?.identifierData, ctx?.helpers),\n\t\t\t);\n\t\t}\n\t}\n\n\t// Call the helper's fn directly with the resolved arguments\n\tconst value = helper.fn(...resolvedArgs);\n\treturn { value };\n}\n"],"names":["Handlebars","dispatchExecute","TemplateRuntimeError","ArrayHelpers","DefaultHelpers","MapHelpers","canUseFastPath","coerceLiteral","extractExpressionIdentifier","extractPathSegments","getEffectiveBody","getEffectivelySingleBlock","getEffectivelySingleExpression","isRootPathTraversal","isRootSegments","isSingleExpression","isThisExpression","parse","ROOT_TOKEN","LRUCache","globalCompilationCache","execute","template","data","identifierData","undefined","tpl","ast","executeFromAst","child","ctx","stmt","body","params","length","hash","resolveExpression","path","helpers","singleExpr","directResult","tryDirectHelperExecution","value","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","coerceValue","coerceSchema","executeFastPath","singleBlock","tryDirectBlockExecution","effective","allContent","every","s","type","targetType","trimmed","trim","num","Number","isNaN","isInteger","lower","toLowerCase","result","String","expr","subExpr","helperName","original","helper","get","isMap","MAP_HELPER_NAME","resolvedArgs","i","param","push","fn","segments","cleanSegments","identifier","source","Array","isArray","map","item","resolveDataPath","filter","v","current","segment","base","id","idData","Object","entries","key","compiledTemplate","cache","compilationCache","hbs","compiled","compile","noEscape","strict","set","error","message","Error","clearCompilationCache","clear","block","condition","isTruthy","branch","program","inverse","nestedBlock","DIRECT_EXECUTION_HELPERS","Set","ARRAY_HELPER_NAME","DEFAULT_HELPER_NAME","has"],"mappings":"AAAA,OAAOA,eAAgB,YAAa,AAEpC,QAASC,eAAe,KAAQ,eAAgB,AAChD,QAASC,oBAAoB,KAAQ,aAAc,AACnD,QAASC,YAAY,KAAQ,4BAA6B,AAC1D,QAASC,cAAc,KAAQ,8BAA+B,AAC9D,QAASC,UAAU,KAAQ,0BAA2B,AACtD,QACCC,cAAc,CACdC,aAAa,CACbC,2BAA2B,CAC3BC,mBAAmB,CACnBC,gBAAgB,CAChBC,yBAAyB,CACzBC,8BAA8B,CAC9BC,mBAAmB,CACnBC,cAAc,CACdC,kBAAkB,CAClBC,gBAAgB,CAChBC,KAAK,CACLC,UAAU,KACJ,aAAc,AAMrB,QAASC,QAAQ,KAAQ,YAAa,CAkEtC,MAAMC,uBAAyB,IAAID,SAClC,IAiBD,QAAO,SAASE,QACfC,QAAuB,CAC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 +1,9 @@
|
|
|
1
|
+
import type { HelperDefinition } from "../types.js";
|
|
2
|
+
import { HelperFactory } from "./helper-factory.js";
|
|
3
|
+
export declare class ArrayHelpers extends HelperFactory {
|
|
4
|
+
/** The name used for special-case detection in the analyzer/executor */
|
|
5
|
+
static readonly ARRAY_HELPER_NAME = "array";
|
|
6
|
+
protected buildDefinitions(defs: Map<string, HelperDefinition>): void;
|
|
7
|
+
/** Registers the `array` helper */
|
|
8
|
+
private registerArray;
|
|
9
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}import{HelperFactory}from"./helper-factory.js";function isHandlebarsOptions(value){return value!==null&&typeof value==="object"&&"hash"in value&&"name"in value}function arrayValue(...args){return args.filter(a=>!isHandlebarsOptions(a))}export class ArrayHelpers extends HelperFactory{buildDefinitions(defs){this.registerArray(defs)}registerArray(defs){defs.set(ArrayHelpers.ARRAY_HELPER_NAME,{fn:arrayValue,params:[{name:"values",description:"One or more values to collect into an array (variadic)"}],description:"Constructs an array from its arguments: {{ array name status }}"})}}_define_property(ArrayHelpers,"ARRAY_HELPER_NAME","array");
|
|
2
|
+
//# sourceMappingURL=array-helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/helpers/array-helpers.ts"],"sourcesContent":["import type { HelperDefinition } from \"../types.ts\";\nimport { HelperFactory } from \"./helper-factory.ts\";\n\n// ─── ArrayHelpers ───────────────────────────────────────────────────────────\n// Provides a variadic helper that constructs an array from its arguments.\n//\n// - **`array`** — Collects all arguments into a single array.\n// Usage: `{{ array name status }}`\n// `{{ array \"a\" \"b\" \"c\" }}`\n// `{{ array (add count 1) 42 }}`\n//\n// ─── Registration ────────────────────────────────────────────────────────────\n// ArrayHelpers are automatically pre-registered by the `Typebars`\n// constructor. They can also be registered manually on any object\n// implementing `HelperRegistry`:\n//\n// const factory = new ArrayHelpers();\n// factory.register(engine); // registers all helpers\n// factory.unregister(engine); // removes all helpers\n//\n// ─── Static Analysis ─────────────────────────────────────────────────────────\n// The `array` helper has special static analysis handling in the analyzer:\n// - At least 1 argument is required\n// - All arguments must have compatible types\n// - The inferred return type is `{ type: \"array\", items: <union of arg types> }`\n\n// ─── Internal utilities ─────────────────────────────────────────────────────\n\n/**\n * Checks whether a value is a Handlebars options object.\n * Handlebars always passes an options object as the last argument to helpers.\n */\nfunction isHandlebarsOptions(value: unknown): boolean {\n\treturn (\n\t\tvalue !== null &&\n\t\ttypeof value === \"object\" &&\n\t\t\"hash\" in (value as Record<string, unknown>) &&\n\t\t\"name\" in (value as Record<string, unknown>)\n\t);\n}\n\n/**\n * Collects all arguments into an array.\n * The trailing Handlebars options object is automatically excluded.\n */\nfunction arrayValue(...args: unknown[]): unknown[] {\n\treturn args.filter((a) => !isHandlebarsOptions(a));\n}\n\n// ─── Main class ─────────────────────────────────────────────────────────────\n\nexport class ArrayHelpers extends HelperFactory {\n\t/** The name used for special-case detection in the analyzer/executor */\n\tstatic readonly ARRAY_HELPER_NAME = \"array\";\n\n\t// ─── buildDefinitions (required by HelperFactory) ──────────────────\n\n\tprotected buildDefinitions(defs: Map<string, HelperDefinition>): void {\n\t\tthis.registerArray(defs);\n\t}\n\n\t// ── array ──────────────────────────────────────────────────────────\n\n\t/** Registers the `array` helper */\n\tprivate registerArray(defs: Map<string, HelperDefinition>): void {\n\t\tdefs.set(ArrayHelpers.ARRAY_HELPER_NAME, {\n\t\t\tfn: arrayValue,\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"values\",\n\t\t\t\t\tdescription: \"One or more values to collect into an array (variadic)\",\n\t\t\t\t},\n\t\t\t],\n\t\t\t// No static returnType — the analyzer infers it from the arguments\n\t\t\tdescription:\n\t\t\t\t\"Constructs an array from its arguments: {{ array name status }}\",\n\t\t});\n\t}\n}\n"],"names":["HelperFactory","isHandlebarsOptions","value","arrayValue","args","filter","a","ArrayHelpers","buildDefinitions","defs","registerArray","set","ARRAY_HELPER_NAME","fn","params","name","description"],"mappings":"oLACA,OAASA,aAAa,KAAQ,qBAAsB,CA+BpD,SAASC,oBAAoBC,KAAc,EAC1C,OACCA,QAAU,MACV,OAAOA,QAAU,UACjB,SAAWA,OACX,SAAWA,KAEb,CAMA,SAASC,WAAW,GAAGC,IAAe,EACrC,OAAOA,KAAKC,MAAM,CAAC,AAACC,GAAM,CAACL,oBAAoBK,GAChD,CAIA,OAAO,MAAMC,qBAAqBP,cAMjC,AAAUQ,iBAAiBC,IAAmC,CAAQ,CACrE,IAAI,CAACC,aAAa,CAACD,KACpB,CAKA,AAAQC,cAAcD,IAAmC,CAAQ,CAChEA,KAAKE,GAAG,CAACJ,aAAaK,iBAAiB,CAAE,CACxCC,GAAIV,WACJW,OAAQ,CACP,CACCC,KAAM,SACNC,YAAa,wDACd,EACA,CAEDA,YACC,iEACF,EACD,CACD,CAzBC,iBAFYT,aAEIK,oBAAoB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{DefaultHelpers}from"./default-helpers.js";export{HelperFactory}from"./helper-factory.js";export{LogicalHelpers}from"./logical-helpers.js";export{MapHelpers}from"./map-helpers.js";export{MathHelpers}from"./math-helpers.js";export{toNumber}from"./utils.js";
|
|
1
|
+
export{ArrayHelpers}from"./array-helpers.js";export{DefaultHelpers}from"./default-helpers.js";export{HelperFactory}from"./helper-factory.js";export{LogicalHelpers}from"./logical-helpers.js";export{MapHelpers}from"./map-helpers.js";export{MathHelpers}from"./math-helpers.js";export{toNumber}from"./utils.js";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/helpers/index.ts"],"sourcesContent":["export { DefaultHelpers } from \"./default-helpers\";\nexport { HelperFactory, type HelperRegistry } from \"./helper-factory\";\nexport { LogicalHelpers } from \"./logical-helpers\";\nexport { MapHelpers } from \"./map-helpers\";\nexport { MathHelpers } from \"./math-helpers\";\nexport { toNumber } from \"./utils\";\n"],"names":["DefaultHelpers","HelperFactory","LogicalHelpers","MapHelpers","MathHelpers","toNumber"],"mappings":"AAAA,OAASA,cAAc,KAAQ,mBAAoB,AACnD,QAASC,aAAa,KAA6B,kBAAmB,AACtE,QAASC,cAAc,KAAQ,mBAAoB,AACnD,QAASC,UAAU,KAAQ,eAAgB,AAC3C,QAASC,WAAW,KAAQ,gBAAiB,AAC7C,QAASC,QAAQ,KAAQ,SAAU"}
|
|
1
|
+
{"version":3,"sources":["../../../src/helpers/index.ts"],"sourcesContent":["export { ArrayHelpers } from \"./array-helpers\";\nexport { DefaultHelpers } from \"./default-helpers\";\nexport { HelperFactory, type HelperRegistry } from \"./helper-factory\";\nexport { LogicalHelpers } from \"./logical-helpers\";\nexport { MapHelpers } from \"./map-helpers\";\nexport { MathHelpers } from \"./math-helpers\";\nexport { toNumber } from \"./utils\";\n"],"names":["ArrayHelpers","DefaultHelpers","HelperFactory","LogicalHelpers","MapHelpers","MathHelpers","toNumber"],"mappings":"AAAA,OAASA,YAAY,KAAQ,iBAAkB,AAC/C,QAASC,cAAc,KAAQ,mBAAoB,AACnD,QAASC,aAAa,KAA6B,kBAAmB,AACtE,QAASC,cAAc,KAAQ,mBAAoB,AACnD,QAASC,UAAU,KAAQ,eAAgB,AAC3C,QAASC,WAAW,KAAQ,gBAAiB,AAC7C,QAASC,QAAQ,KAAQ,SAAU"}
|
package/dist/esm/parser.d.ts
CHANGED
|
@@ -38,6 +38,14 @@ export declare function extractPathSegments(expr: hbs.AST.Expression): string[];
|
|
|
38
38
|
* (used inside `{{#each}}` blocks).
|
|
39
39
|
*/
|
|
40
40
|
export declare function isThisExpression(expr: hbs.AST.Expression): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Checks whether an AST expression is a Handlebars `@data` variable
|
|
43
|
+
* (e.g. `@index`, `@first`, `@last`, `@key`).
|
|
44
|
+
*
|
|
45
|
+
* These variables are injected by Handlebars at runtime inside block helpers
|
|
46
|
+
* and are not part of the user-provided input schema.
|
|
47
|
+
*/
|
|
48
|
+
export declare function isDataExpression(expr: hbs.AST.Expression): boolean;
|
|
41
49
|
/**
|
|
42
50
|
* Checks whether an AST expression is a `PathExpression` whose first
|
|
43
51
|
* segment is the `$root` token.
|
package/dist/esm/parser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import Handlebars from"handlebars";import{TemplateParseError}from"./errors.js";export const ROOT_TOKEN="$root";const IDENTIFIER_RE=/^(.+):(-?\d+)$/;const NUMERIC_LITERAL_RE=/^-?\d+(\.\d+)?$/;export function parse(template){try{return Handlebars.parse(template)}catch(error){const message=error instanceof Error?error.message:String(error);const locMatch=message.match(/line\s+(\d+).*?column\s+(\d+)/i);const loc=locMatch?{line:parseInt(locMatch[1]??"0",10),column:parseInt(locMatch[2]??"0",10)}:undefined;throw new TemplateParseError(message,loc)}}export function isSingleExpression(ast){const{body}=ast;return body.length===1&&body[0]?.type==="MustacheStatement"}export function extractPathSegments(expr){if(expr.type==="PathExpression"){return expr.parts}return[]}export function isThisExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.original==="this"||path.original==="."}export function isRootExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.parts.length>0&&path.parts[0]===ROOT_TOKEN}export function isRootSegments(cleanSegments){return cleanSegments.length===1&&cleanSegments[0]===ROOT_TOKEN}export function isRootPathTraversal(cleanSegments){return cleanSegments.length>1&&cleanSegments[0]===ROOT_TOKEN}export function getEffectiveBody(program){return program.body.filter(s=>!(s.type==="ContentStatement"&&s.value.trim()===""))}export function getEffectivelySingleBlock(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="BlockStatement"){return effective[0]}return null}export function getEffectivelySingleExpression(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="MustacheStatement"){return effective[0]}return null}export function hasHandlebarsExpression(value){return value.includes("{{")}export function canUseFastPath(ast){return ast.body.every(s=>s.type==="ContentStatement"||s.type==="MustacheStatement"&&s.params.length===0&&!s.hash)}export function detectLiteralType(text){if(NUMERIC_LITERAL_RE.test(text))return"number";if(text==="true"||text==="false")return"boolean";if(text==="null")return"null";return null}export function coerceLiteral(raw){const trimmed=raw.trim();const type=detectLiteralType(trimmed);if(type==="number")return Number(trimmed);if(type==="boolean")return trimmed==="true";if(type==="null")return null;return raw}export function parseIdentifier(segment){const match=segment.match(IDENTIFIER_RE);if(match){return{key:match[1]??segment,identifier:parseInt(match[2]??"0",10)}}return{key:segment,identifier:null}}export function extractExpressionIdentifier(segments){if(segments.length===0){return{cleanSegments:[],identifier:null}}const lastSegment=segments[segments.length-1];const parsed=parseIdentifier(lastSegment);if(parsed.identifier!==null){const cleanSegments=[...segments.slice(0,-1),parsed.key];return{cleanSegments,identifier:parsed.identifier}}return{cleanSegments:segments,identifier:null}}
|
|
1
|
+
import Handlebars from"handlebars";import{TemplateParseError}from"./errors.js";export const ROOT_TOKEN="$root";const IDENTIFIER_RE=/^(.+):(-?\d+)$/;const NUMERIC_LITERAL_RE=/^-?\d+(\.\d+)?$/;export function parse(template){try{return Handlebars.parse(template)}catch(error){const message=error instanceof Error?error.message:String(error);const locMatch=message.match(/line\s+(\d+).*?column\s+(\d+)/i);const loc=locMatch?{line:parseInt(locMatch[1]??"0",10),column:parseInt(locMatch[2]??"0",10)}:undefined;throw new TemplateParseError(message,loc)}}export function isSingleExpression(ast){const{body}=ast;return body.length===1&&body[0]?.type==="MustacheStatement"}export function extractPathSegments(expr){if(expr.type==="PathExpression"){return expr.parts}return[]}export function isThisExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.original==="this"||path.original==="."}export function isDataExpression(expr){if(expr.type!=="PathExpression")return false;return expr.data===true}export function isRootExpression(expr){if(expr.type!=="PathExpression")return false;const path=expr;return path.parts.length>0&&path.parts[0]===ROOT_TOKEN}export function isRootSegments(cleanSegments){return cleanSegments.length===1&&cleanSegments[0]===ROOT_TOKEN}export function isRootPathTraversal(cleanSegments){return cleanSegments.length>1&&cleanSegments[0]===ROOT_TOKEN}export function getEffectiveBody(program){return program.body.filter(s=>!(s.type==="ContentStatement"&&s.value.trim()===""))}export function getEffectivelySingleBlock(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="BlockStatement"){return effective[0]}return null}export function getEffectivelySingleExpression(program){const effective=getEffectiveBody(program);if(effective.length===1&&effective[0]?.type==="MustacheStatement"){return effective[0]}return null}export function hasHandlebarsExpression(value){return value.includes("{{")}export function canUseFastPath(ast){return ast.body.every(s=>s.type==="ContentStatement"||s.type==="MustacheStatement"&&s.params.length===0&&!s.hash)}export function detectLiteralType(text){if(NUMERIC_LITERAL_RE.test(text))return"number";if(text==="true"||text==="false")return"boolean";if(text==="null")return"null";return null}export function coerceLiteral(raw){const trimmed=raw.trim();const type=detectLiteralType(trimmed);if(type==="number")return Number(trimmed);if(type==="boolean")return trimmed==="true";if(type==="null")return null;return raw}export function parseIdentifier(segment){const match=segment.match(IDENTIFIER_RE);if(match){return{key:match[1]??segment,identifier:parseInt(match[2]??"0",10)}}return{key:segment,identifier:null}}export function extractExpressionIdentifier(segments){if(segments.length===0){return{cleanSegments:[],identifier:null}}const lastSegment=segments[segments.length-1];const parsed=parseIdentifier(lastSegment);if(parsed.identifier!==null){const cleanSegments=[...segments.slice(0,-1),parsed.key];return{cleanSegments,identifier:parsed.identifier}}return{cleanSegments:segments,identifier:null}}
|
|
2
2
|
//# sourceMappingURL=parser.js.map
|
package/dist/esm/parser.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/parser.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport { TemplateParseError } from \"./errors.ts\";\n\n// ─── Root Token ──────────────────────────────────────────────────────────────\n// Special token `$root` references the entire input schema / data context.\n// It cannot be followed by property access (e.g. `$root.name` is invalid).\nexport const ROOT_TOKEN = \"$root\";\n\n// ─── Regex for detecting a template identifier (e.g. \"meetingId:1\") ──────────\n// The identifier is always an integer (positive, zero, or negative),\n// separated from the variable name by a `:`. The `:` and number are on\n// the **last** segment of the path (Handlebars splits on `.`).\nconst IDENTIFIER_RE = /^(.+):(-?\\d+)$/;\n\n// ─── Template Parser ─────────────────────────────────────────────────────────\n// Thin wrapper around the Handlebars parser. Centralizing the parser call\n// here allows us to:\n// 1. Wrap errors into our own hierarchy (`TemplateParseError`)\n// 2. Expose AST introspection helpers (e.g. `isSingleExpression`)\n// 3. Isolate the direct Handlebars dependency from the rest of the codebase\n//\n// AST caching is handled at the `Typebars` instance level (via its own\n// configurable LRU cache), not here. This module only parses and wraps errors.\n\n// ─── Regex for detecting a numeric literal (integer or decimal, signed) ──────\n// Intentionally conservative: no scientific notation (1e5), no hex (0xFF),\n// no separators (1_000). We only want to recognize what a human would write\n// as a numeric value in a template.\nconst NUMERIC_LITERAL_RE = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Parses a template string and returns the Handlebars AST.\n *\n * This function does not cache results — caching is managed at the\n * `Typebars` instance level via its own configurable LRU cache.\n *\n * @param template - The template string to parse (e.g. `\"Hello {{name}}\"`)\n * @returns The root AST node (`hbs.AST.Program`)\n * @throws {TemplateParseError} if the template syntax is invalid\n */\nexport function parse(template: string): hbs.AST.Program {\n\ttry {\n\t\treturn Handlebars.parse(template);\n\t} catch (error: unknown) {\n\t\t// Handlebars throws a plain Error with a descriptive message.\n\t\t// We transform it into a TemplateParseError for uniform handling.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\n\t\t// Handlebars sometimes includes the position in the message —\n\t\t// attempt to extract it to enrich our error.\n\t\tconst locMatch = message.match(/line\\s+(\\d+).*?column\\s+(\\d+)/i);\n\t\tconst loc = locMatch\n\t\t\t? {\n\t\t\t\t\tline: parseInt(locMatch[1] ?? \"0\", 10),\n\t\t\t\t\tcolumn: parseInt(locMatch[2] ?? \"0\", 10),\n\t\t\t\t}\n\t\t\t: undefined;\n\n\t\tthrow new TemplateParseError(message, loc);\n\t}\n}\n\n/**\n * Determines whether the AST represents a template consisting of a single\n * expression `{{expression}}` with no text content around it.\n *\n * This matters for return type inference:\n * - Template `{{value}}` → returns the raw type of `value` (number, object…)\n * - Template `Hello {{name}}` → always returns `string` (concatenation)\n *\n * @param ast - The parsed AST of the template\n * @returns `true` if the template is a single expression\n */\nexport function isSingleExpression(ast: hbs.AST.Program): boolean {\n\tconst { body } = ast;\n\n\t// Exactly one node, and it's a MustacheStatement (not a block, not text)\n\treturn body.length === 1 && body[0]?.type === \"MustacheStatement\";\n}\n\n/**\n * Extracts the path segments from a Handlebars `PathExpression`.\n *\n * Handlebars decomposes `user.address.city` into `{ parts: [\"user\", \"address\", \"city\"] }`.\n * This function safely extracts those segments.\n *\n * @param expr - The expression to extract the path from\n * @returns The path segments, or an empty array if the expression is not\n * a `PathExpression`\n */\nexport function extractPathSegments(expr: hbs.AST.Expression): string[] {\n\tif (expr.type === \"PathExpression\") {\n\t\treturn (expr as hbs.AST.PathExpression).parts;\n\t}\n\treturn [];\n}\n\n/**\n * Checks whether an AST expression is a `PathExpression` pointing to `this`\n * (used inside `{{#each}}` blocks).\n */\nexport function isThisExpression(expr: hbs.AST.Expression): boolean {\n\tif (expr.type !== \"PathExpression\") return false;\n\tconst path = expr as hbs.AST.PathExpression;\n\treturn path.original === \"this\" || path.original === \".\";\n}\n\n/**\n * Checks whether an AST expression is a `PathExpression` whose first\n * segment is the `$root` token.\n *\n * This covers both the valid `{{$root}}` case (single segment) and the\n * invalid `{{$root.name}}` case (multiple segments). The caller must\n * check `parts.length` to distinguish valid from invalid usage.\n *\n * **Note:** This does NOT match `{{$root:2}}` because Handlebars parses\n * it as `parts: [\"$root:2\"]` (identifier still attached). Use\n * `isRootSegments()` on cleaned segments instead when identifier\n * extraction has already been performed.\n */\nexport function isRootExpression(expr: hbs.AST.Expression): boolean {\n\tif (expr.type !== \"PathExpression\") return false;\n\tconst path = expr as hbs.AST.PathExpression;\n\treturn path.parts.length > 0 && path.parts[0] === ROOT_TOKEN;\n}\n\n/**\n * Checks whether an array of **cleaned** path segments represents a\n * `$root` reference (i.e. exactly one segment equal to `\"$root\"`).\n *\n * This is the segment-level counterpart of `isRootExpression()` and is\n * meant to be called **after** `extractExpressionIdentifier()` has\n * stripped the `:N` suffix. It correctly handles both `{{$root}}` and\n * `{{$root:2}}`.\n *\n * @param cleanSegments - Path segments with identifiers already removed\n * @returns `true` if the segments represent a `$root` reference\n */\nexport function isRootSegments(cleanSegments: string[]): boolean {\n\treturn cleanSegments.length === 1 && cleanSegments[0] === ROOT_TOKEN;\n}\n\n/**\n * Checks whether cleaned segments represent a **path traversal** on\n * `$root` (e.g. `$root.name`, `$root.address.city`).\n *\n * Path traversal on `$root` is forbidden — users should write `{{name}}`\n * instead of `{{$root.name}}`.\n *\n * @param cleanSegments - Path segments with identifiers already removed\n * @returns `true` if the first segment is `$root` and there are additional segments\n */\nexport function isRootPathTraversal(cleanSegments: string[]): boolean {\n\treturn cleanSegments.length > 1 && cleanSegments[0] === ROOT_TOKEN;\n}\n\n// ─── Filtering Semantically Significant Nodes ───────────────────────────────\n// In a Handlebars AST, formatting (newlines, indentation) produces\n// `ContentStatement` nodes whose value is purely whitespace. These nodes\n// have no semantic impact and must be ignored during type inference to\n// correctly detect \"effectively a single block\" or \"effectively a single\n// expression\" cases.\n\n/**\n * Returns the semantically significant statements of a Program by\n * filtering out `ContentStatement` nodes that contain only whitespace.\n */\nexport function getEffectiveBody(\n\tprogram: hbs.AST.Program,\n): hbs.AST.Statement[] {\n\treturn program.body.filter(\n\t\t(s) =>\n\t\t\t!(\n\t\t\t\ts.type === \"ContentStatement\" &&\n\t\t\t\t(s as hbs.AST.ContentStatement).value.trim() === \"\"\n\t\t\t),\n\t);\n}\n\n/**\n * Determines whether a Program effectively consists of a single\n * `BlockStatement` (ignoring surrounding whitespace).\n *\n * Recognized examples:\n * ```\n * {{#if x}}...{{/if}}\n *\n * {{#each items}}...{{/each}}\n * ```\n *\n * @returns The single `BlockStatement`, or `null` if the program contains\n * other significant nodes.\n */\nexport function getEffectivelySingleBlock(\n\tprogram: hbs.AST.Program,\n): hbs.AST.BlockStatement | null {\n\tconst effective = getEffectiveBody(program);\n\tif (effective.length === 1 && effective[0]?.type === \"BlockStatement\") {\n\t\treturn effective[0] as hbs.AST.BlockStatement;\n\t}\n\treturn null;\n}\n\n/**\n * Determines whether a Program effectively consists of a single\n * `MustacheStatement` (ignoring surrounding whitespace).\n *\n * Example: ` {{age}} ` → true\n */\nexport function getEffectivelySingleExpression(\n\tprogram: hbs.AST.Program,\n): hbs.AST.MustacheStatement | null {\n\tconst effective = getEffectiveBody(program);\n\tif (effective.length === 1 && effective[0]?.type === \"MustacheStatement\") {\n\t\treturn effective[0] as hbs.AST.MustacheStatement;\n\t}\n\treturn null;\n}\n\n// ─── Handlebars Expression Detection ─────────────────────────────────────────\n// Fast heuristic to determine whether a string contains Handlebars expressions.\n// Used by `excludeTemplateExpression` filtering to skip dynamic entries.\n\n/**\n * Determines whether a string contains Handlebars expressions.\n *\n * A string contains template expressions if it includes `{{` (opening\n * delimiter for Handlebars mustache/block statements). This is a fast\n * substring check — **no parsing is performed**.\n *\n * Used by `excludeTemplateExpression` to filter out properties whose\n * values are dynamic templates.\n *\n * **Limitation:** This is a simple `includes(\"{{\")` check, not a full\n * parser. It will produce false positives for strings that contain `{{`\n * as literal text (e.g. `\"Use {{name}} syntax\"` in documentation strings)\n * or in escaped contexts. For the current use case (filtering object/array\n * entries that are likely templates), this trade-off is acceptable because:\n * - It avoids the cost of parsing every string value\n * - False positives only cause an entry to be excluded from the output\n * schema (conservative behavior)\n *\n * @param value - The string to check\n * @returns `true` if the string contains at least one `{{` sequence\n */\nexport function hasHandlebarsExpression(value: string): boolean {\n\treturn value.includes(\"{{\");\n}\n\n// ─── Fast-Path Detection ─────────────────────────────────────────────────────\n// For templates consisting only of text and simple expressions (no blocks,\n// no helpers with parameters), we can bypass Handlebars entirely and perform\n// a simple variable replacement via string concatenation.\n\n/**\n * Determines whether an AST can be executed via the fast-path (direct\n * concatenation without going through `Handlebars.compile()`).\n *\n * The fast-path is possible when the template only contains:\n * - `ContentStatement` nodes (static text)\n * - Simple `MustacheStatement` nodes (no params, no hash)\n *\n * This excludes:\n * - Block helpers (`{{#if}}`, `{{#each}}`, etc.)\n * - Inline helpers (`{{uppercase name}}`)\n * - Sub-expressions\n *\n * @param ast - The parsed AST of the template\n * @returns `true` if the template can use the fast-path\n */\nexport function canUseFastPath(ast: hbs.AST.Program): boolean {\n\treturn ast.body.every(\n\t\t(s) =>\n\t\t\ts.type === \"ContentStatement\" ||\n\t\t\t(s.type === \"MustacheStatement\" &&\n\t\t\t\t(s as hbs.AST.MustacheStatement).params.length === 0 &&\n\t\t\t\t!(s as hbs.AST.MustacheStatement).hash),\n\t);\n}\n\n// ─── Literal Detection in Text Content ───────────────────────────────────────\n// When a program contains only ContentStatements (no expressions), we try\n// to detect whether the concatenated and trimmed text is a typed literal\n// (number, boolean, null). This enables correct type inference for branches\n// like `{{#if x}} 42 {{/if}}`.\n\n/**\n * Attempts to detect the type of a raw text literal.\n *\n * @param text - The trimmed text from a ContentStatement or group of ContentStatements\n * @returns The detected JSON Schema type, or `null` if it's free-form text (string).\n */\nexport function detectLiteralType(\n\ttext: string,\n): \"number\" | \"boolean\" | \"null\" | null {\n\tif (NUMERIC_LITERAL_RE.test(text)) return \"number\";\n\tif (text === \"true\" || text === \"false\") return \"boolean\";\n\tif (text === \"null\") return \"null\";\n\treturn null;\n}\n\n/**\n * Coerces a raw string from Handlebars rendering to its actual type\n * if it represents a literal (number, boolean, null).\n * Returns the raw (untrimmed) string otherwise.\n */\nexport function coerceLiteral(raw: string): unknown {\n\tconst trimmed = raw.trim();\n\tconst type = detectLiteralType(trimmed);\n\tif (type === \"number\") return Number(trimmed);\n\tif (type === \"boolean\") return trimmed === \"true\";\n\tif (type === \"null\") return null;\n\t// Not a typed literal — return the raw string without trimming,\n\t// as whitespace may be significant (e.g. output of an #each block).\n\treturn raw;\n}\n\n// ─── Template Identifier Parsing ─────────────────────────────────────────────\n// Syntax `{{key:N}}` where N is an integer (positive, zero, or negative).\n// The identifier allows resolving a variable from a specific data source\n// (e.g. a workflow node identified by its number).\n\n/** Result of parsing a path segment with a potential identifier */\nexport interface ParsedIdentifier {\n\t/** The variable name, without the `:N` suffix */\n\tkey: string;\n\t/** The numeric identifier, or `null` if absent */\n\tidentifier: number | null;\n}\n\n/**\n * Parses an individual path segment to extract the key and optional identifier.\n *\n * @param segment - A raw path segment (e.g. `\"meetingId:1\"` or `\"meetingId\"`)\n * @returns An object `{ key, identifier }`\n *\n * @example\n * ```\n * parseIdentifier(\"meetingId:1\") // → { key: \"meetingId\", identifier: 1 }\n * parseIdentifier(\"meetingId\") // → { key: \"meetingId\", identifier: null }\n * parseIdentifier(\"meetingId:0\") // → { key: \"meetingId\", identifier: 0 }\n * ```\n */\nexport function parseIdentifier(segment: string): ParsedIdentifier {\n\tconst match = segment.match(IDENTIFIER_RE);\n\tif (match) {\n\t\treturn {\n\t\t\tkey: match[1] ?? segment,\n\t\t\tidentifier: parseInt(match[2] ?? \"0\", 10),\n\t\t};\n\t}\n\treturn { key: segment, identifier: null };\n}\n\n/** Result of extracting the identifier from a complete expression */\nexport interface ExpressionIdentifier {\n\t/** Cleaned path segments (without the `:N` suffix on the last one) */\n\tcleanSegments: string[];\n\t/** The numeric identifier extracted from the last segment, or `null` */\n\tidentifier: number | null;\n}\n\n/**\n * Extracts the identifier from a complete expression (array of segments).\n *\n * The identifier is always on the **last** segment of the path, because\n * Handlebars splits on `.` before the `:`.\n *\n * @param segments - The raw path segments (e.g. `[\"user\", \"name:1\"]`)\n * @returns An object `{ cleanSegments, identifier }`\n *\n * @example\n * ```\n * extractExpressionIdentifier([\"meetingId:1\"])\n * // → { cleanSegments: [\"meetingId\"], identifier: 1 }\n *\n * extractExpressionIdentifier([\"user\", \"name:1\"])\n * // → { cleanSegments: [\"user\", \"name\"], identifier: 1 }\n *\n * extractExpressionIdentifier([\"meetingId\"])\n * // → { cleanSegments: [\"meetingId\"], identifier: null }\n * ```\n */\nexport function extractExpressionIdentifier(\n\tsegments: string[],\n): ExpressionIdentifier {\n\tif (segments.length === 0) {\n\t\treturn { cleanSegments: [], identifier: null };\n\t}\n\n\tconst lastSegment = segments[segments.length - 1] as string;\n\tconst parsed = parseIdentifier(lastSegment);\n\n\tif (parsed.identifier !== null) {\n\t\tconst cleanSegments = [...segments.slice(0, -1), parsed.key];\n\t\treturn { cleanSegments, identifier: parsed.identifier };\n\t}\n\n\treturn { cleanSegments: segments, identifier: null };\n}\n"],"names":["Handlebars","TemplateParseError","ROOT_TOKEN","IDENTIFIER_RE","NUMERIC_LITERAL_RE","parse","template","error","message","Error","String","locMatch","match","loc","line","parseInt","column","undefined","isSingleExpression","ast","body","length","type","extractPathSegments","expr","parts","isThisExpression","path","original","isRootExpression","isRootSegments","cleanSegments","isRootPathTraversal","getEffectiveBody","program","filter","s","value","trim","getEffectivelySingleBlock","effective","getEffectivelySingleExpression","hasHandlebarsExpression","includes","canUseFastPath","every","params","hash","detectLiteralType","text","test","coerceLiteral","raw","trimmed","Number","parseIdentifier","segment","key","identifier","extractExpressionIdentifier","segments","lastSegment","parsed","slice"],"mappings":"AAAA,OAAOA,eAAgB,YAAa,AACpC,QAASC,kBAAkB,KAAQ,aAAc,AAKjD,QAAO,MAAMC,WAAa,OAAQ,CAMlC,MAAMC,cAAgB,iBAgBtB,MAAMC,mBAAqB,iBAY3B,QAAO,SAASC,MAAMC,QAAgB,EACrC,GAAI,CACH,OAAON,WAAWK,KAAK,CAACC,SACzB,CAAE,MAAOC,MAAgB,CAGxB,MAAMC,QAAUD,iBAAiBE,MAAQF,MAAMC,OAAO,CAAGE,OAAOH,OAIhE,MAAMI,SAAWH,QAAQI,KAAK,CAAC,kCAC/B,MAAMC,IAAMF,SACT,CACAG,KAAMC,SAASJ,QAAQ,CAAC,EAAE,EAAI,IAAK,IACnCK,OAAQD,SAASJ,QAAQ,CAAC,EAAE,EAAI,IAAK,GACt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,QAASE,WAAY,IAAK,CACzC,CA+BA,OAAO,SAASC,4BACfC,QAAkB,EAElB,GAAIA,SAASvC,MAAM,GAAK,EAAG,CAC1B,MAAO,CAAEU,cAAe,EAAE,CAAE2B,WAAY,IAAK,CAC9C,CAEA,MAAMG,YAAcD,QAAQ,CAACA,SAASvC,MAAM,CAAG,EAAE,CACjD,MAAMyC,OAASP,gBAAgBM,aAE/B,GAAIC,OAAOJ,UAAU,GAAK,KAAM,CAC/B,MAAM3B,cAAgB,IAAI6B,SAASG,KAAK,CAAC,EAAG,CAAC,GAAID,OAAOL,GAAG,CAAC,CAC5D,MAAO,CAAE1B,cAAe2B,WAAYI,OAAOJ,UAAU,AAAC,CACvD,CAEA,MAAO,CAAE3B,cAAe6B,SAAUF,WAAY,IAAK,CACpD"}
|
|
1
|
+
{"version":3,"sources":["../../src/parser.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport { TemplateParseError } from \"./errors.ts\";\n\n// ─── Root Token ──────────────────────────────────────────────────────────────\n// Special token `$root` references the entire input schema / data context.\n// It cannot be followed by property access (e.g. `$root.name` is invalid).\nexport const ROOT_TOKEN = \"$root\";\n\n// ─── Regex for detecting a template identifier (e.g. \"meetingId:1\") ──────────\n// The identifier is always an integer (positive, zero, or negative),\n// separated from the variable name by a `:`. The `:` and number are on\n// the **last** segment of the path (Handlebars splits on `.`).\nconst IDENTIFIER_RE = /^(.+):(-?\\d+)$/;\n\n// ─── Template Parser ─────────────────────────────────────────────────────────\n// Thin wrapper around the Handlebars parser. Centralizing the parser call\n// here allows us to:\n// 1. Wrap errors into our own hierarchy (`TemplateParseError`)\n// 2. Expose AST introspection helpers (e.g. `isSingleExpression`)\n// 3. Isolate the direct Handlebars dependency from the rest of the codebase\n//\n// AST caching is handled at the `Typebars` instance level (via its own\n// configurable LRU cache), not here. This module only parses and wraps errors.\n\n// ─── Regex for detecting a numeric literal (integer or decimal, signed) ──────\n// Intentionally conservative: no scientific notation (1e5), no hex (0xFF),\n// no separators (1_000). We only want to recognize what a human would write\n// as a numeric value in a template.\nconst NUMERIC_LITERAL_RE = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Parses a template string and returns the Handlebars AST.\n *\n * This function does not cache results — caching is managed at the\n * `Typebars` instance level via its own configurable LRU cache.\n *\n * @param template - The template string to parse (e.g. `\"Hello {{name}}\"`)\n * @returns The root AST node (`hbs.AST.Program`)\n * @throws {TemplateParseError} if the template syntax is invalid\n */\nexport function parse(template: string): hbs.AST.Program {\n\ttry {\n\t\treturn Handlebars.parse(template);\n\t} catch (error: unknown) {\n\t\t// Handlebars throws a plain Error with a descriptive message.\n\t\t// We transform it into a TemplateParseError for uniform handling.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\n\t\t// Handlebars sometimes includes the position in the message —\n\t\t// attempt to extract it to enrich our error.\n\t\tconst locMatch = message.match(/line\\s+(\\d+).*?column\\s+(\\d+)/i);\n\t\tconst loc = locMatch\n\t\t\t? {\n\t\t\t\t\tline: parseInt(locMatch[1] ?? \"0\", 10),\n\t\t\t\t\tcolumn: parseInt(locMatch[2] ?? \"0\", 10),\n\t\t\t\t}\n\t\t\t: undefined;\n\n\t\tthrow new TemplateParseError(message, loc);\n\t}\n}\n\n/**\n * Determines whether the AST represents a template consisting of a single\n * expression `{{expression}}` with no text content around it.\n *\n * This matters for return type inference:\n * - Template `{{value}}` → returns the raw type of `value` (number, object…)\n * - Template `Hello {{name}}` → always returns `string` (concatenation)\n *\n * @param ast - The parsed AST of the template\n * @returns `true` if the template is a single expression\n */\nexport function isSingleExpression(ast: hbs.AST.Program): boolean {\n\tconst { body } = ast;\n\n\t// Exactly one node, and it's a MustacheStatement (not a block, not text)\n\treturn body.length === 1 && body[0]?.type === \"MustacheStatement\";\n}\n\n/**\n * Extracts the path segments from a Handlebars `PathExpression`.\n *\n * Handlebars decomposes `user.address.city` into `{ parts: [\"user\", \"address\", \"city\"] }`.\n * This function safely extracts those segments.\n *\n * @param expr - The expression to extract the path from\n * @returns The path segments, or an empty array if the expression is not\n * a `PathExpression`\n */\nexport function extractPathSegments(expr: hbs.AST.Expression): string[] {\n\tif (expr.type === \"PathExpression\") {\n\t\treturn (expr as hbs.AST.PathExpression).parts;\n\t}\n\treturn [];\n}\n\n/**\n * Checks whether an AST expression is a `PathExpression` pointing to `this`\n * (used inside `{{#each}}` blocks).\n */\nexport function isThisExpression(expr: hbs.AST.Expression): boolean {\n\tif (expr.type !== \"PathExpression\") return false;\n\tconst path = expr as hbs.AST.PathExpression;\n\treturn path.original === \"this\" || path.original === \".\";\n}\n\n/**\n * Checks whether an AST expression is a Handlebars `@data` variable\n * (e.g. `@index`, `@first`, `@last`, `@key`).\n *\n * These variables are injected by Handlebars at runtime inside block helpers\n * and are not part of the user-provided input schema.\n */\nexport function isDataExpression(expr: hbs.AST.Expression): boolean {\n\tif (expr.type !== \"PathExpression\") return false;\n\treturn (expr as hbs.AST.PathExpression).data === true;\n}\n\n/**\n * Checks whether an AST expression is a `PathExpression` whose first\n * segment is the `$root` token.\n *\n * This covers both the valid `{{$root}}` case (single segment) and the\n * invalid `{{$root.name}}` case (multiple segments). The caller must\n * check `parts.length` to distinguish valid from invalid usage.\n *\n * **Note:** This does NOT match `{{$root:2}}` because Handlebars parses\n * it as `parts: [\"$root:2\"]` (identifier still attached). Use\n * `isRootSegments()` on cleaned segments instead when identifier\n * extraction has already been performed.\n */\nexport function isRootExpression(expr: hbs.AST.Expression): boolean {\n\tif (expr.type !== \"PathExpression\") return false;\n\tconst path = expr as hbs.AST.PathExpression;\n\treturn path.parts.length > 0 && path.parts[0] === ROOT_TOKEN;\n}\n\n/**\n * Checks whether an array of **cleaned** path segments represents a\n * `$root` reference (i.e. exactly one segment equal to `\"$root\"`).\n *\n * This is the segment-level counterpart of `isRootExpression()` and is\n * meant to be called **after** `extractExpressionIdentifier()` has\n * stripped the `:N` suffix. It correctly handles both `{{$root}}` and\n * `{{$root:2}}`.\n *\n * @param cleanSegments - Path segments with identifiers already removed\n * @returns `true` if the segments represent a `$root` reference\n */\nexport function isRootSegments(cleanSegments: string[]): boolean {\n\treturn cleanSegments.length === 1 && cleanSegments[0] === ROOT_TOKEN;\n}\n\n/**\n * Checks whether cleaned segments represent a **path traversal** on\n * `$root` (e.g. `$root.name`, `$root.address.city`).\n *\n * Path traversal on `$root` is forbidden — users should write `{{name}}`\n * instead of `{{$root.name}}`.\n *\n * @param cleanSegments - Path segments with identifiers already removed\n * @returns `true` if the first segment is `$root` and there are additional segments\n */\nexport function isRootPathTraversal(cleanSegments: string[]): boolean {\n\treturn cleanSegments.length > 1 && cleanSegments[0] === ROOT_TOKEN;\n}\n\n// ─── Filtering Semantically Significant Nodes ───────────────────────────────\n// In a Handlebars AST, formatting (newlines, indentation) produces\n// `ContentStatement` nodes whose value is purely whitespace. These nodes\n// have no semantic impact and must be ignored during type inference to\n// correctly detect \"effectively a single block\" or \"effectively a single\n// expression\" cases.\n\n/**\n * Returns the semantically significant statements of a Program by\n * filtering out `ContentStatement` nodes that contain only whitespace.\n */\nexport function getEffectiveBody(\n\tprogram: hbs.AST.Program,\n): hbs.AST.Statement[] {\n\treturn program.body.filter(\n\t\t(s) =>\n\t\t\t!(\n\t\t\t\ts.type === \"ContentStatement\" &&\n\t\t\t\t(s as hbs.AST.ContentStatement).value.trim() === \"\"\n\t\t\t),\n\t);\n}\n\n/**\n * Determines whether a Program effectively consists of a single\n * `BlockStatement` (ignoring surrounding whitespace).\n *\n * Recognized examples:\n * ```\n * {{#if x}}...{{/if}}\n *\n * {{#each items}}...{{/each}}\n * ```\n *\n * @returns The single `BlockStatement`, or `null` if the program contains\n * other significant nodes.\n */\nexport function getEffectivelySingleBlock(\n\tprogram: hbs.AST.Program,\n): hbs.AST.BlockStatement | null {\n\tconst effective = getEffectiveBody(program);\n\tif (effective.length === 1 && effective[0]?.type === \"BlockStatement\") {\n\t\treturn effective[0] as hbs.AST.BlockStatement;\n\t}\n\treturn null;\n}\n\n/**\n * Determines whether a Program effectively consists of a single\n * `MustacheStatement` (ignoring surrounding whitespace).\n *\n * Example: ` {{age}} ` → true\n */\nexport function getEffectivelySingleExpression(\n\tprogram: hbs.AST.Program,\n): hbs.AST.MustacheStatement | null {\n\tconst effective = getEffectiveBody(program);\n\tif (effective.length === 1 && effective[0]?.type === \"MustacheStatement\") {\n\t\treturn effective[0] as hbs.AST.MustacheStatement;\n\t}\n\treturn null;\n}\n\n// ─── Handlebars Expression Detection ─────────────────────────────────────────\n// Fast heuristic to determine whether a string contains Handlebars expressions.\n// Used by `excludeTemplateExpression` filtering to skip dynamic entries.\n\n/**\n * Determines whether a string contains Handlebars expressions.\n *\n * A string contains template expressions if it includes `{{` (opening\n * delimiter for Handlebars mustache/block statements). This is a fast\n * substring check — **no parsing is performed**.\n *\n * Used by `excludeTemplateExpression` to filter out properties whose\n * values are dynamic templates.\n *\n * **Limitation:** This is a simple `includes(\"{{\")` check, not a full\n * parser. It will produce false positives for strings that contain `{{`\n * as literal text (e.g. `\"Use {{name}} syntax\"` in documentation strings)\n * or in escaped contexts. For the current use case (filtering object/array\n * entries that are likely templates), this trade-off is acceptable because:\n * - It avoids the cost of parsing every string value\n * - False positives only cause an entry to be excluded from the output\n * schema (conservative behavior)\n *\n * @param value - The string to check\n * @returns `true` if the string contains at least one `{{` sequence\n */\nexport function hasHandlebarsExpression(value: string): boolean {\n\treturn value.includes(\"{{\");\n}\n\n// ─── Fast-Path Detection ─────────────────────────────────────────────────────\n// For templates consisting only of text and simple expressions (no blocks,\n// no helpers with parameters), we can bypass Handlebars entirely and perform\n// a simple variable replacement via string concatenation.\n\n/**\n * Determines whether an AST can be executed via the fast-path (direct\n * concatenation without going through `Handlebars.compile()`).\n *\n * The fast-path is possible when the template only contains:\n * - `ContentStatement` nodes (static text)\n * - Simple `MustacheStatement` nodes (no params, no hash)\n *\n * This excludes:\n * - Block helpers (`{{#if}}`, `{{#each}}`, etc.)\n * - Inline helpers (`{{uppercase name}}`)\n * - Sub-expressions\n *\n * @param ast - The parsed AST of the template\n * @returns `true` if the template can use the fast-path\n */\nexport function canUseFastPath(ast: hbs.AST.Program): boolean {\n\treturn ast.body.every(\n\t\t(s) =>\n\t\t\ts.type === \"ContentStatement\" ||\n\t\t\t(s.type === \"MustacheStatement\" &&\n\t\t\t\t(s as hbs.AST.MustacheStatement).params.length === 0 &&\n\t\t\t\t!(s as hbs.AST.MustacheStatement).hash),\n\t);\n}\n\n// ─── Literal Detection in Text Content ───────────────────────────────────────\n// When a program contains only ContentStatements (no expressions), we try\n// to detect whether the concatenated and trimmed text is a typed literal\n// (number, boolean, null). This enables correct type inference for branches\n// like `{{#if x}} 42 {{/if}}`.\n\n/**\n * Attempts to detect the type of a raw text literal.\n *\n * @param text - The trimmed text from a ContentStatement or group of ContentStatements\n * @returns The detected JSON Schema type, or `null` if it's free-form text (string).\n */\nexport function detectLiteralType(\n\ttext: string,\n): \"number\" | \"boolean\" | \"null\" | null {\n\tif (NUMERIC_LITERAL_RE.test(text)) return \"number\";\n\tif (text === \"true\" || text === \"false\") return \"boolean\";\n\tif (text === \"null\") return \"null\";\n\treturn null;\n}\n\n/**\n * Coerces a raw string from Handlebars rendering to its actual type\n * if it represents a literal (number, boolean, null).\n * Returns the raw (untrimmed) string otherwise.\n */\nexport function coerceLiteral(raw: string): unknown {\n\tconst trimmed = raw.trim();\n\tconst type = detectLiteralType(trimmed);\n\tif (type === \"number\") return Number(trimmed);\n\tif (type === \"boolean\") return trimmed === \"true\";\n\tif (type === \"null\") return null;\n\t// Not a typed literal — return the raw string without trimming,\n\t// as whitespace may be significant (e.g. output of an #each block).\n\treturn raw;\n}\n\n// ─── Template Identifier Parsing ─────────────────────────────────────────────\n// Syntax `{{key:N}}` where N is an integer (positive, zero, or negative).\n// The identifier allows resolving a variable from a specific data source\n// (e.g. a workflow node identified by its number).\n\n/** Result of parsing a path segment with a potential identifier */\nexport interface ParsedIdentifier {\n\t/** The variable name, without the `:N` suffix */\n\tkey: string;\n\t/** The numeric identifier, or `null` if absent */\n\tidentifier: number | null;\n}\n\n/**\n * Parses an individual path segment to extract the key and optional identifier.\n *\n * @param segment - A raw path segment (e.g. `\"meetingId:1\"` or `\"meetingId\"`)\n * @returns An object `{ key, identifier }`\n *\n * @example\n * ```\n * parseIdentifier(\"meetingId:1\") // → { key: \"meetingId\", identifier: 1 }\n * parseIdentifier(\"meetingId\") // → { key: \"meetingId\", identifier: null }\n * parseIdentifier(\"meetingId:0\") // → { key: \"meetingId\", identifier: 0 }\n * ```\n */\nexport function parseIdentifier(segment: string): ParsedIdentifier {\n\tconst match = segment.match(IDENTIFIER_RE);\n\tif (match) {\n\t\treturn {\n\t\t\tkey: match[1] ?? segment,\n\t\t\tidentifier: parseInt(match[2] ?? \"0\", 10),\n\t\t};\n\t}\n\treturn { key: segment, identifier: null };\n}\n\n/** Result of extracting the identifier from a complete expression */\nexport interface ExpressionIdentifier {\n\t/** Cleaned path segments (without the `:N` suffix on the last one) */\n\tcleanSegments: string[];\n\t/** The numeric identifier extracted from the last segment, or `null` */\n\tidentifier: number | null;\n}\n\n/**\n * Extracts the identifier from a complete expression (array of segments).\n *\n * The identifier is always on the **last** segment of the path, because\n * Handlebars splits on `.` before the `:`.\n *\n * @param segments - The raw path segments (e.g. `[\"user\", \"name:1\"]`)\n * @returns An object `{ cleanSegments, identifier }`\n *\n * @example\n * ```\n * extractExpressionIdentifier([\"meetingId:1\"])\n * // → { cleanSegments: [\"meetingId\"], identifier: 1 }\n *\n * extractExpressionIdentifier([\"user\", \"name:1\"])\n * // → { cleanSegments: [\"user\", \"name\"], identifier: 1 }\n *\n * extractExpressionIdentifier([\"meetingId\"])\n * // → { cleanSegments: [\"meetingId\"], identifier: null }\n * ```\n */\nexport function extractExpressionIdentifier(\n\tsegments: string[],\n): ExpressionIdentifier {\n\tif (segments.length === 0) {\n\t\treturn { cleanSegments: [], identifier: null };\n\t}\n\n\tconst lastSegment = segments[segments.length - 1] as string;\n\tconst parsed = parseIdentifier(lastSegment);\n\n\tif (parsed.identifier !== null) {\n\t\tconst cleanSegments = [...segments.slice(0, -1), parsed.key];\n\t\treturn { cleanSegments, identifier: parsed.identifier };\n\t}\n\n\treturn { cleanSegments: segments, identifier: null };\n}\n"],"names":["Handlebars","TemplateParseError","ROOT_TOKEN","IDENTIFIER_RE","NUMERIC_LITERAL_RE","parse","template","error","message","Error","String","locMatch","match","loc","line","parseInt","column","undefined","isSingleExpression","ast","body","length","type","extractPathSegments","expr","parts","isThisExpression","path","original","isDataExpression","data","isRootExpression","isRootSegments","cleanSegments","isRootPathTraversal","getEffectiveBody","program","filter","s","value","trim","getEffectivelySingleBlock","effective","getEffectivelySingleExpression","hasHandlebarsExpression","includes","canUseFastPath","every","params","hash","detectLiteralType","text","test","coerceLiteral","raw","trimmed","Number","parseIdentifier","segment","key","identifier","extractExpressionIdentifier","segments","lastSegment","parsed","slice"],"mappings":"AAAA,OAAOA,eAAgB,YAAa,AACpC,QAASC,kBAAkB,KAAQ,aAAc,AAKjD,QAAO,MAAMC,WAAa,OAAQ,CAMlC,MAAMC,cAAgB,iBAgBtB,MAAMC,mBAAqB,iBAY3B,QAAO,SAASC,MAAMC,QAAgB,EACrC,GAAI,CACH,OAAON,WAAWK,KAAK,CAACC,SACzB,CAAE,MAAOC,MAAgB,CAGxB,MAAMC,QAAUD,iBAAiBE,MAAQF,MAAMC,OAAO,CAAGE,OAAOH,OAIhE,MAAMI,SAAWH,QAAQI,KAAK,CAAC,kCAC/B,MAAMC,IAAMF,SACT,CACAG,KAAMC,SAASJ,QAAQ,CAAC,EAAE,EAAI,IAAK,IACnCK,OAAQD,SAASJ,QAAQ,CAAC,EAAE,EAAI,IAAK,GACtC,EACCM,SAEH,OAAM,IAAIhB,mBAAmBO,QAASK,IACvC,CACD,CAaA,OAAO,SAASK,mBAAmBC,GAAoB,EACtD,KAAM,CAAEC,IAAI,CAAE,CAAGD,IAGjB,OAAOC,KAAKC,MAAM,GAAK,GAAKD,IAAI,CAAC,EAAE,EAAEE,OAAS,mBAC/C,CAYA,OAAO,SAASC,oBAAo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,EAAG,CAC1B,MAAO,CAAEY,cAAe,EAAE,CAAE2B,WAAY,IAAK,CAC9C,CAEA,MAAMG,YAAcD,QAAQ,CAACA,SAASzC,MAAM,CAAG,EAAE,CACjD,MAAM2C,OAASP,gBAAgBM,aAE/B,GAAIC,OAAOJ,UAAU,GAAK,KAAM,CAC/B,MAAM3B,cAAgB,IAAI6B,SAASG,KAAK,CAAC,EAAG,CAAC,GAAID,OAAOL,GAAG,CAAC,CAC5D,MAAO,CAAE1B,cAAe2B,WAAYI,OAAOJ,UAAU,AAAC,CACvD,CAEA,MAAO,CAAE3B,cAAe6B,SAAUF,WAAY,IAAK,CACpD"}
|
package/dist/esm/typebars.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}import Handlebars from"handlebars";import{analyzeFromAst}from"./analyzer.js";import{CompiledTemplate}from"./compiled-template.js";import{dispatchAnalyze,dispatchAnalyzeAndExecute,dispatchExecute}from"./dispatch.js";import{TemplateAnalysisError}from"./errors.js";import{executeFromAst}from"./executor.js";import{DefaultHelpers,LogicalHelpers,MapHelpers,MathHelpers}from"./helpers/index.js";import{parse}from"./parser.js";import{isArrayInput,isLiteralInput,isObjectInput}from"./types.js";import{LRUCache}from"./utils.js";const DIRECT_EXECUTION_HELPER_NAMES=new Set([MapHelpers.MAP_HELPER_NAME]);function stringifyForTemplate(value){if(value===null||value===undefined)return"";if(Array.isArray(value)){return value.map(item=>{if(item===null||item===undefined)return"";if(typeof item==="object")return JSON.stringify(item);return String(item)}).join(", ")}return String(value)}export class Typebars{compile(template){if(isArrayInput(template)){const children=[];for(const element of template){children.push(this.compile(element))}return CompiledTemplate.fromArray(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if(isObjectInput(template)){const children={};for(const[key,value]of Object.entries(template)){children[key]=this.compile(value)}return CompiledTemplate.fromObject(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if(isLiteralInput(template)){return CompiledTemplate.fromLiteral(template,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}const ast=this.getCachedAst(template);const options={helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache};return CompiledTemplate.fromTemplate(ast,template,options)}analyze(template,inputSchema={},options){return dispatchAnalyze(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);return analyzeFromAst(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema})},(child,childOptions)=>this.analyze(child,inputSchema,childOptions))}validate(template,inputSchema={},options){const analysis=this.analyze(template,inputSchema,options);return{valid:analysis.valid,diagnostics:analysis.diagnostics}}isValidSyntax(template){if(isArrayInput(template)){return template.every(v=>this.isValidSyntax(v))}if(isObjectInput(template)){return Object.values(template).every(v=>this.isValidSyntax(v))}if(isLiteralInput(template))return true;try{this.getCachedAst(template);return true}catch{return false}}execute(template,data,options){return dispatchExecute(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);if(options?.schema){const analysis=analyzeFromAst(ast,tpl,options.schema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers});if(!analysis.valid){throw new TemplateAnalysisError(analysis.diagnostics)}}return executeFromAst(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema,helpers:this.helpers})},(child,childOptions)=>this.execute(child,data,{...options,...childOptions}))}analyzeAndExecute(template,inputSchema={},data,options){return dispatchAnalyzeAndExecute(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);const analysis=analyzeFromAst(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema});if(!analysis.valid){return{analysis,value:undefined}}const value=executeFromAst(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema,helpers:this.helpers});return{analysis,value}},(child,childOptions)=>this.analyzeAndExecute(child,inputSchema,data,childOptions))}registerHelper(name,definition){this.helpers.set(name,definition);if(DIRECT_EXECUTION_HELPER_NAMES.has(name)){this.hbs.registerHelper(name,(...args)=>{const hbsArgs=args.slice(0,-1);const raw=definition.fn(...hbsArgs);return stringifyForTemplate(raw)})}else{this.hbs.registerHelper(name,definition.fn)}this.compilationCache.clear();return this}unregisterHelper(name){this.helpers.delete(name);this.hbs.unregisterHelper(name);this.compilationCache.clear();return this}hasHelper(name){return this.helpers.has(name)}clearCaches(){this.astCache.clear();this.compilationCache.clear()}getCachedAst(template){let ast=this.astCache.get(template);if(!ast){ast=parse(template);this.astCache.set(template,ast)}return ast}constructor(options={}){_define_property(this,"hbs",void 0);_define_property(this,"astCache",void 0);_define_property(this,"compilationCache",void 0);_define_property(this,"helpers",new Map);this.hbs=Handlebars.create();this.astCache=new LRUCache(options.astCacheSize??256);this.compilationCache=new LRUCache(options.compilationCacheSize??256);new MathHelpers().register(this);new LogicalHelpers().register(this);new MapHelpers().register(this);new DefaultHelpers().register(this);if(options.helpers){for(const helper of options.helpers){const{name,...definition}=helper;this.registerHelper(name,definition)}}}}
|
|
1
|
+
function _define_property(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}import Handlebars from"handlebars";import{analyzeFromAst}from"./analyzer.js";import{CompiledTemplate}from"./compiled-template.js";import{dispatchAnalyze,dispatchAnalyzeAndExecute,dispatchExecute}from"./dispatch.js";import{TemplateAnalysisError}from"./errors.js";import{executeFromAst}from"./executor.js";import{ArrayHelpers,DefaultHelpers,LogicalHelpers,MapHelpers,MathHelpers}from"./helpers/index.js";import{parse}from"./parser.js";import{isArrayInput,isLiteralInput,isObjectInput}from"./types.js";import{LRUCache}from"./utils.js";const DIRECT_EXECUTION_HELPER_NAMES=new Set([ArrayHelpers.ARRAY_HELPER_NAME,MapHelpers.MAP_HELPER_NAME]);function stringifyForTemplate(value){if(value===null||value===undefined)return"";if(Array.isArray(value)){return value.map(item=>{if(item===null||item===undefined)return"";if(typeof item==="object")return JSON.stringify(item);return String(item)}).join(", ")}return String(value)}export class Typebars{compile(template){if(isArrayInput(template)){const children=[];for(const element of template){children.push(this.compile(element))}return CompiledTemplate.fromArray(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if(isObjectInput(template)){const children={};for(const[key,value]of Object.entries(template)){children[key]=this.compile(value)}return CompiledTemplate.fromObject(children,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}if(isLiteralInput(template)){return CompiledTemplate.fromLiteral(template,{helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache})}const ast=this.getCachedAst(template);const options={helpers:this.helpers,hbs:this.hbs,compilationCache:this.compilationCache};return CompiledTemplate.fromTemplate(ast,template,options)}analyze(template,inputSchema={},options){return dispatchAnalyze(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);return analyzeFromAst(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema})},(child,childOptions)=>this.analyze(child,inputSchema,childOptions))}validate(template,inputSchema={},options){const analysis=this.analyze(template,inputSchema,options);return{valid:analysis.valid,diagnostics:analysis.diagnostics}}isValidSyntax(template){if(isArrayInput(template)){return template.every(v=>this.isValidSyntax(v))}if(isObjectInput(template)){return Object.values(template).every(v=>this.isValidSyntax(v))}if(isLiteralInput(template))return true;try{this.getCachedAst(template);return true}catch{return false}}execute(template,data,options){return dispatchExecute(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);if(options?.schema){const analysis=analyzeFromAst(ast,tpl,options.schema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers});if(!analysis.valid){throw new TemplateAnalysisError(analysis.diagnostics)}}return executeFromAst(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema,helpers:this.helpers})},(child,childOptions)=>this.execute(child,data,{...options,...childOptions}))}analyzeAndExecute(template,inputSchema={},data,options){return dispatchAnalyzeAndExecute(template,options,(tpl,coerceSchema)=>{const ast=this.getCachedAst(tpl);const analysis=analyzeFromAst(ast,tpl,inputSchema,{identifierSchemas:options?.identifierSchemas,helpers:this.helpers,coerceSchema});if(!analysis.valid){return{analysis,value:undefined}}const value=executeFromAst(ast,tpl,data,{identifierData:options?.identifierData,hbs:this.hbs,compilationCache:this.compilationCache,coerceSchema,helpers:this.helpers});return{analysis,value}},(child,childOptions)=>this.analyzeAndExecute(child,inputSchema,data,childOptions))}registerHelper(name,definition){this.helpers.set(name,definition);if(DIRECT_EXECUTION_HELPER_NAMES.has(name)){this.hbs.registerHelper(name,(...args)=>{const hbsArgs=args.slice(0,-1);const raw=definition.fn(...hbsArgs);return stringifyForTemplate(raw)})}else{this.hbs.registerHelper(name,definition.fn)}this.compilationCache.clear();return this}unregisterHelper(name){this.helpers.delete(name);this.hbs.unregisterHelper(name);this.compilationCache.clear();return this}hasHelper(name){return this.helpers.has(name)}clearCaches(){this.astCache.clear();this.compilationCache.clear()}getCachedAst(template){let ast=this.astCache.get(template);if(!ast){ast=parse(template);this.astCache.set(template,ast)}return ast}constructor(options={}){_define_property(this,"hbs",void 0);_define_property(this,"astCache",void 0);_define_property(this,"compilationCache",void 0);_define_property(this,"helpers",new Map);this.hbs=Handlebars.create();this.astCache=new LRUCache(options.astCacheSize??256);this.compilationCache=new LRUCache(options.compilationCacheSize??256);new ArrayHelpers().register(this);new MathHelpers().register(this);new LogicalHelpers().register(this);new MapHelpers().register(this);new DefaultHelpers().register(this);if(options.helpers){for(const helper of options.helpers){const{name,...definition}=helper;this.registerHelper(name,definition)}}}}
|
|
2
2
|
//# sourceMappingURL=typebars.js.map
|
package/dist/esm/typebars.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/typebars.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type { AnalyzeOptions } from \"./analyzer.ts\";\nimport { analyzeFromAst } from \"./analyzer.ts\";\nimport {\n\tCompiledTemplate,\n\ttype CompiledTemplateOptions,\n} from \"./compiled-template.ts\";\nimport {\n\tdispatchAnalyze,\n\tdispatchAnalyzeAndExecute,\n\tdispatchExecute,\n} from \"./dispatch.ts\";\nimport { TemplateAnalysisError } from \"./errors.ts\";\nimport { executeFromAst } from \"./executor.ts\";\nimport {\n\tDefaultHelpers,\n\tLogicalHelpers,\n\tMapHelpers,\n\tMathHelpers,\n} from \"./helpers/index.ts\";\nimport { parse } from \"./parser.ts\";\nimport type {\n\tAnalysisResult,\n\tAnalyzeAndExecuteOptions,\n\tExecuteOptions,\n\tHelperDefinition,\n\tTemplateData,\n\tTemplateEngineOptions,\n\tTemplateInput,\n\tValidationResult,\n} from \"./types.ts\";\nimport { isArrayInput, isLiteralInput, isObjectInput } from \"./types.ts\";\nimport { LRUCache } from \"./utils\";\n\n// ─── Typebars ────────────────────────────────────────────────────────────────\n// Public entry point of the template engine. Orchestrates three phases:\n//\n// 1. **Parsing** — transforms the template string into an AST (via Handlebars)\n// 2. **Analysis** — static validation + return type inference\n// 3. **Execution** — renders the template with real data\n//\n// ─── Architecture v2 ─────────────────────────────────────────────────────────\n// - **LRU cache** for parsed ASTs and compiled Handlebars templates\n// - **Isolated Handlebars environment** per instance (custom helpers)\n// - **`compile()` pattern**: parse-once / execute-many\n// - **`validate()` method**: API shortcut without `outputSchema`\n// - **`registerHelper()`**: custom helpers with static typing\n// - **`ExecuteOptions`**: options object for `execute()`\n//\n// ─── Template Identifiers ────────────────────────────────────────────────────\n// The `{{key:N}}` syntax allows referencing variables from specific data\n// sources, identified by an integer N.\n//\n// - `identifierSchemas`: mapping `{ [id]: JSONSchema7 }` for static analysis\n// - `identifierData`: mapping `{ [id]: Record<string, unknown> }` for execution\n//\n// Usage:\n// engine.execute(\"{{meetingId:1}}\", data, { identifierData: { 1: node1Data } });\n// engine.analyze(\"{{meetingId:1}}\", schema, { identifierSchemas: { 1: node1Schema } });\n\n// ─── Direct Execution Helper Names ───────────────────────────────────────────\n// Helpers whose return values are non-primitive (arrays, objects) and must be\n// wrapped when registered with Handlebars so that mixed/block templates get a\n// human-readable string (e.g. `\", \"` joined) instead of JS default toString().\n// In single-expression mode the executor bypasses Handlebars entirely, so the\n// raw value is preserved.\nconst DIRECT_EXECUTION_HELPER_NAMES = new Set<string>([\n\tMapHelpers.MAP_HELPER_NAME,\n]);\n\n/**\n * Converts a value to a string suitable for embedding in a Handlebars template.\n *\n * - Arrays of primitives are joined with `\", \"`\n * - Arrays of objects are JSON-stringified per element, then joined\n * - Primitives use `String(value)`\n * - null/undefined become `\"\"`\n */\nfunction stringifyForTemplate(value: unknown): string {\n\tif (value === null || value === undefined) return \"\";\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.map((item) => {\n\t\t\t\tif (item === null || item === undefined) return \"\";\n\t\t\t\tif (typeof item === \"object\") return JSON.stringify(item);\n\t\t\t\treturn String(item);\n\t\t\t})\n\t\t\t.join(\", \");\n\t}\n\treturn String(value);\n}\n\n// ─── Main Class ──────────────────────────────────────────────────────────────\n\nexport class Typebars {\n\t/** Isolated Handlebars environment — each engine has its own helpers */\n\tprivate readonly hbs: typeof Handlebars;\n\n\t/** LRU cache of parsed ASTs (avoids re-parsing) */\n\tprivate readonly astCache: LRUCache<string, hbs.AST.Program>;\n\n\t/** LRU cache of compiled Handlebars templates (avoids recompilation) */\n\tprivate readonly compilationCache: LRUCache<\n\t\tstring,\n\t\tHandlebarsTemplateDelegate\n\t>;\n\n\t/** Custom helpers registered on this instance */\n\tprivate readonly helpers = new Map<string, HelperDefinition>();\n\n\tconstructor(options: TemplateEngineOptions = {}) {\n\t\tthis.hbs = Handlebars.create();\n\t\tthis.astCache = new LRUCache(options.astCacheSize ?? 256);\n\t\tthis.compilationCache = new LRUCache(options.compilationCacheSize ?? 256);\n\n\t\t// ── Built-in helpers ─────────────────────────────────────────────\n\t\tnew MathHelpers().register(this);\n\t\tnew LogicalHelpers().register(this);\n\t\tnew MapHelpers().register(this);\n\t\tnew DefaultHelpers().register(this);\n\n\t\t// ── Custom helpers via options ───────────────────────────────────\n\t\tif (options.helpers) {\n\t\t\tfor (const helper of options.helpers) {\n\t\t\t\tconst { name, ...definition } = helper;\n\t\t\t\tthis.registerHelper(name, definition);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Compilation ───────────────────────────────────────────────────────\n\n\t/**\n\t * Compiles a template and returns a `CompiledTemplate` ready to be\n\t * executed or analyzed without re-parsing.\n\t *\n\t * Accepts a `TemplateInput`: string, number, boolean, null, or object.\n\t * For objects, each property is compiled recursively.\n\t *\n\t * @param template - The template to compile\n\t * @returns A reusable `CompiledTemplate`\n\t */\n\tcompile(template: TemplateInput): CompiledTemplate {\n\t\tif (isArrayInput(template)) {\n\t\t\tconst children: CompiledTemplate[] = [];\n\t\t\tfor (const element of template) {\n\t\t\t\tchildren.push(this.compile(element));\n\t\t\t}\n\t\t\treturn CompiledTemplate.fromArray(children, {\n\t\t\t\thelpers: this.helpers,\n\t\t\t\thbs: this.hbs,\n\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t});\n\t\t}\n\t\tif (isObjectInput(template)) {\n\t\t\tconst children: Record<string, CompiledTemplate> = {};\n\t\t\tfor (const [key, value] of Object.entries(template)) {\n\t\t\t\tchildren[key] = this.compile(value);\n\t\t\t}\n\t\t\treturn CompiledTemplate.fromObject(children, {\n\t\t\t\thelpers: this.helpers,\n\t\t\t\thbs: this.hbs,\n\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t});\n\t\t}\n\t\tif (isLiteralInput(template)) {\n\t\t\treturn CompiledTemplate.fromLiteral(template, {\n\t\t\t\thelpers: this.helpers,\n\t\t\t\thbs: this.hbs,\n\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t});\n\t\t}\n\t\tconst ast = this.getCachedAst(template);\n\t\tconst options: CompiledTemplateOptions = {\n\t\t\thelpers: this.helpers,\n\t\t\thbs: this.hbs,\n\t\t\tcompilationCache: this.compilationCache,\n\t\t};\n\t\treturn CompiledTemplate.fromTemplate(ast, template, options);\n\t}\n\n\t// ─── Static Analysis ─────────────────────────────────────────────────────\n\n\t/**\n\t * Statically analyzes a template against a JSON Schema v7 describing\n\t * the available context.\n\t *\n\t * Accepts a `TemplateInput`: string, number, boolean, null, or object.\n\t * For objects, each property is analyzed recursively and the\n\t * `outputSchema` reflects the object structure with resolved types.\n\t *\n\t * @param template - The template to analyze\n\t * @param inputSchema - JSON Schema v7 describing the available variables\n\t * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n\t */\n\tanalyze(\n\t\ttemplate: TemplateInput,\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): AnalysisResult {\n\t\treturn dispatchAnalyze(\n\t\t\ttemplate,\n\t\t\toptions,\n\t\t\t// String handler — parse with cache and analyze the AST\n\t\t\t(tpl, coerceSchema) => {\n\t\t\t\tconst ast = this.getCachedAst(tpl);\n\t\t\t\treturn analyzeFromAst(ast, tpl, inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t});\n\t\t\t},\n\t\t\t// Recursive handler — re-enter analyze() for child elements\n\t\t\t(child, childOptions) => this.analyze(child, inputSchema, childOptions),\n\t\t);\n\t}\n\n\t// ─── Validation ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Validates a template against a schema without returning the output type.\n\t *\n\t * This is an API shortcut for `analyze()` that only returns `valid` and\n\t * `diagnostics`, without `outputSchema`. The full analysis (including type\n\t * inference) is executed internally — this method provides no performance\n\t * gain, only a simplified API.\n\t *\n\t * @param template - The template to validate\n\t * @param inputSchema - JSON Schema v7 describing the available variables\n\t * @param identifierSchemas - (optional) Schemas by identifier\n\t */\n\tvalidate(\n\t\ttemplate: TemplateInput,\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): ValidationResult {\n\t\tconst analysis = this.analyze(template, inputSchema, options);\n\t\treturn {\n\t\t\tvalid: analysis.valid,\n\t\t\tdiagnostics: analysis.diagnostics,\n\t\t};\n\t}\n\n\t// ─── Syntax Validation ───────────────────────────────────────────────────\n\n\t/**\n\t * Checks only that the template syntax is valid (parsing).\n\t * Does not require a schema — useful for quick feedback in an editor.\n\t *\n\t * For objects, recursively checks each property.\n\t *\n\t * @param template - The template to validate\n\t * @returns `true` if the template is syntactically correct\n\t */\n\tisValidSyntax(template: TemplateInput): boolean {\n\t\tif (isArrayInput(template)) {\n\t\t\treturn template.every((v) => this.isValidSyntax(v));\n\t\t}\n\t\tif (isObjectInput(template)) {\n\t\t\treturn Object.values(template).every((v) => this.isValidSyntax(v));\n\t\t}\n\t\tif (isLiteralInput(template)) return true;\n\t\ttry {\n\t\t\tthis.getCachedAst(template);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// ─── Execution ───────────────────────────────────────────────────────────\n\n\t/**\n\t * Executes a template with the provided data.\n\t *\n\t * Accepts a `TemplateInput`: string, number, boolean, null, or object.\n\t * For objects, each property is executed recursively and an object with\n\t * resolved values is returned.\n\t *\n\t * If a `schema` is provided in options, static analysis is performed\n\t * before execution. A `TemplateAnalysisError` is thrown on errors.\n\t *\n\t * @param template - The template to execute\n\t * @param data - The context data for rendering\n\t * @param options - Execution options (schema, identifierData, identifierSchemas)\n\t * @returns The execution result\n\t */\n\texecute(\n\t\ttemplate: TemplateInput,\n\t\tdata?: TemplateData,\n\t\toptions?: ExecuteOptions,\n\t): unknown {\n\t\treturn dispatchExecute(\n\t\t\ttemplate,\n\t\t\toptions,\n\t\t\t// String handler — parse, optionally validate, then execute\n\t\t\t(tpl, coerceSchema) => {\n\t\t\t\tconst ast = this.getCachedAst(tpl);\n\n\t\t\t\t// Pre-execution static validation if a schema is provided\n\t\t\t\tif (options?.schema) {\n\t\t\t\t\tconst analysis = analyzeFromAst(ast, tpl, options.schema, {\n\t\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t\t});\n\t\t\t\t\tif (!analysis.valid) {\n\t\t\t\t\t\tthrow new TemplateAnalysisError(analysis.diagnostics);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn executeFromAst(ast, tpl, data, {\n\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\thbs: this.hbs,\n\t\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t});\n\t\t\t},\n\t\t\t// Recursive handler — re-enter execute() for child elements\n\t\t\t(child, childOptions) =>\n\t\t\t\tthis.execute(child, data, { ...options, ...childOptions }),\n\t\t);\n\t}\n\n\t// ─── Combined Shortcuts ──────────────────────────────────────────────────\n\n\t/**\n\t * Analyzes a template and, if valid, executes it with the provided data.\n\t * Returns both the analysis result and the executed value.\n\t *\n\t * For objects, each property is analyzed and executed recursively.\n\t * The entire object is considered invalid if at least one property is.\n\t *\n\t * @param template - The template\n\t * @param inputSchema - JSON Schema v7 describing the available variables\n\t * @param data - The context data for rendering\n\t * @param options - (optional) Options for template identifiers\n\t * @returns An object `{ analysis, value }` where `value` is `undefined`\n\t * if analysis failed.\n\t */\n\tanalyzeAndExecute(\n\t\ttemplate: TemplateInput,\n\t\tinputSchema: JSONSchema7 = {},\n\t\tdata: TemplateData,\n\t\toptions?: AnalyzeAndExecuteOptions,\n\t): { analysis: AnalysisResult; value: unknown } {\n\t\treturn dispatchAnalyzeAndExecute(\n\t\t\ttemplate,\n\t\t\toptions,\n\t\t\t// String handler — analyze then execute if valid\n\t\t\t(tpl, coerceSchema) => {\n\t\t\t\tconst ast = this.getCachedAst(tpl);\n\t\t\t\tconst analysis = analyzeFromAst(ast, tpl, inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t});\n\n\t\t\t\tif (!analysis.valid) {\n\t\t\t\t\treturn { analysis, value: undefined };\n\t\t\t\t}\n\n\t\t\t\tconst value = executeFromAst(ast, tpl, data, {\n\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\thbs: this.hbs,\n\t\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t});\n\t\t\t\treturn { analysis, value };\n\t\t\t},\n\t\t\t// Recursive handler — re-enter analyzeAndExecute() for child elements\n\t\t\t(child, childOptions) =>\n\t\t\t\tthis.analyzeAndExecute(child, inputSchema, data, childOptions),\n\t\t);\n\t}\n\n\t// ─── Custom Helper Management ──────────────────────────────────────────\n\n\t/**\n\t * Registers a custom helper on this engine instance.\n\t *\n\t * The helper is available for both execution (via Handlebars) and\n\t * static analysis (via its declared `returnType`).\n\t *\n\t * @param name - Helper name (e.g. `\"uppercase\"`)\n\t * @param definition - Helper definition (implementation + return type)\n\t * @returns `this` to allow chaining\n\t */\n\tregisterHelper(name: string, definition: HelperDefinition): this {\n\t\tthis.helpers.set(name, definition);\n\n\t\t// For helpers that return non-primitive values (arrays, objects),\n\t\t// register a Handlebars-friendly wrapper that converts the result\n\t\t// to a string. In single-expression mode the executor bypasses\n\t\t// Handlebars entirely (via tryDirectHelperExecution) and returns\n\t\t// the raw value, so this wrapper only affects mixed/block templates\n\t\t// where Handlebars renders the result into a larger string.\n\t\tif (DIRECT_EXECUTION_HELPER_NAMES.has(name)) {\n\t\t\tthis.hbs.registerHelper(name, (...args: unknown[]) => {\n\t\t\t\t// Handlebars appends an `options` object as the last argument.\n\t\t\t\t// Strip it before calling the real fn.\n\t\t\t\tconst hbsArgs = args.slice(0, -1);\n\t\t\t\tconst raw = definition.fn(...hbsArgs);\n\t\t\t\treturn stringifyForTemplate(raw);\n\t\t\t});\n\t\t} else {\n\t\t\tthis.hbs.registerHelper(name, definition.fn);\n\t\t}\n\n\t\t// Invalidate the compilation cache because helpers have changed\n\t\tthis.compilationCache.clear();\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes a custom helper from this engine instance.\n\t *\n\t * @param name - Name of the helper to remove\n\t * @returns `this` to allow chaining\n\t */\n\tunregisterHelper(name: string): this {\n\t\tthis.helpers.delete(name);\n\t\tthis.hbs.unregisterHelper(name);\n\n\t\t// Invalidate the compilation cache\n\t\tthis.compilationCache.clear();\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Checks whether a helper is registered on this instance.\n\t *\n\t * @param name - Helper name\n\t * @returns `true` if the helper is registered\n\t */\n\thasHelper(name: string): boolean {\n\t\treturn this.helpers.has(name);\n\t}\n\n\t// ─── Cache Management ──────────────────────────────────────────────────\n\n\t/**\n\t * Clears all internal caches (AST + compilation).\n\t *\n\t * Useful after a configuration change or to free memory.\n\t */\n\tclearCaches(): void {\n\t\tthis.astCache.clear();\n\t\tthis.compilationCache.clear();\n\t}\n\n\t// ─── Internals ─────────────────────────────────────────────────────────\n\n\t/**\n\t * Retrieves the AST of a template from the cache, or parses and caches it.\n\t */\n\tprivate getCachedAst(template: string): hbs.AST.Program {\n\t\tlet ast = this.astCache.get(template);\n\t\tif (!ast) {\n\t\t\tast = parse(template);\n\t\t\tthis.astCache.set(template, ast);\n\t\t}\n\t\treturn ast;\n\t}\n}\n"],"names":["Handlebars","analyzeFromAst","CompiledTemplate","dispatchAnalyze","dispatchAnalyzeAndExecute","dispatchExecute","TemplateAnalysisError","executeFromAst","DefaultHelpers","LogicalHelpers","MapHelpers","MathHelpers","parse","isArrayInput","isLiteralInput","isObjectInput","LRUCache","DIRECT_EXECUTION_HELPER_NAMES","Set","MAP_HELPER_NAME","stringifyForTemplate","value","undefined","Array","isArray","map","item","JSON","stringify","String","join","Typebars","compile","template","children","element","push","fromArray","helpers","hbs","compilationCache","key","Object","entries","fromObject","fromLiteral","ast","getCachedAst","options","fromTemplate","analyze","inputSchema","tpl","coerceSchema","identifierSchemas","child","childOptions","validate","analysis","valid","diagnostics","isValidSyntax","every","v","values","execute","data","schema","identifierData","analyzeAndExecute","registerHelper","name","definition","set","has","args","hbsArgs","slice","raw","fn","clear","unregisterHelper","delete","hasHelper","clearCaches","astCache","get","Map","create","astCacheSize","compilationCacheSize","register","helper"],"mappings":"oLAAA,OAAOA,eAAgB,YAAa,AAGpC,QAASC,cAAc,KAAQ,eAAgB,AAC/C,QACCC,gBAAgB,KAEV,wBAAyB,AAChC,QACCC,eAAe,CACfC,yBAAyB,CACzBC,eAAe,KACT,eAAgB,AACvB,QAASC,qBAAqB,KAAQ,aAAc,AACpD,QAASC,cAAc,KAAQ,eAAgB,AAC/C,QACCC,cAAc,CACdC,cAAc,CACdC,UAAU,CACVC,WAAW,KACL,oBAAqB,AAC5B,QAASC,KAAK,KAAQ,aAAc,AAWpC,QAASC,YAAY,CAAEC,cAAc,CAAEC,aAAa,KAAQ,YAAa,AACzE,QAASC,QAAQ,KAAQ,SAAU,CAkCnC,MAAMC,8BAAgC,IAAIC,IAAY,CACrDR,WAAWS,eAAe,CAC1B,EAUD,SAASC,qBAAqBC,KAAc,EAC3C,GAAIA,QAAU,MAAQA,QAAUC,UAAW,MAAO,GAClD,GAAIC,MAAMC,OAAO,CAACH,OAAQ,CACzB,OAAOA,MACLI,GAAG,CAAC,AAACC,OACL,GAAIA,OAAS,MAAQA,OAASJ,UAAW,MAAO,GAChD,GAAI,OAAOI,OAAS,SAAU,OAAOC,KAAKC,SAAS,CAACF,MACpD,OAAOG,OAAOH,KACf,GACCI,IAAI,CAAC,KACR,CACA,OAAOD,OAAOR,MACf,CAIA,OAAO,MAAMU,SAgDZC,QAAQC,QAAuB,CAAoB,CAClD,GAAIpB,aAAaoB,UAAW,CAC3B,MAAMC,SAA+B,EAAE,CACvC,IAAK,MAAMC,WAAWF,SAAU,CAC/BC,SAASE,IAAI,CAAC,IAAI,CAACJ,OAAO,CAACG,SAC5B,CACA,OAAOjC,iBAA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,KAAM,CAAEiC,IAAI,CAAE,GAAGC,WAAY,CAAGoB,OAChC,IAAI,CAACtB,cAAc,CAACC,KAAMC,WAC3B,CACD,CACD,CAmVD"}
|
|
1
|
+
{"version":3,"sources":["../../src/typebars.ts"],"sourcesContent":["import Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type { AnalyzeOptions } from \"./analyzer.ts\";\nimport { analyzeFromAst } from \"./analyzer.ts\";\nimport {\n\tCompiledTemplate,\n\ttype CompiledTemplateOptions,\n} from \"./compiled-template.ts\";\nimport {\n\tdispatchAnalyze,\n\tdispatchAnalyzeAndExecute,\n\tdispatchExecute,\n} from \"./dispatch.ts\";\nimport { TemplateAnalysisError } from \"./errors.ts\";\nimport { executeFromAst } from \"./executor.ts\";\nimport {\n\tArrayHelpers,\n\tDefaultHelpers,\n\tLogicalHelpers,\n\tMapHelpers,\n\tMathHelpers,\n} from \"./helpers/index.ts\";\nimport { parse } from \"./parser.ts\";\nimport type {\n\tAnalysisResult,\n\tAnalyzeAndExecuteOptions,\n\tExecuteOptions,\n\tHelperDefinition,\n\tTemplateData,\n\tTemplateEngineOptions,\n\tTemplateInput,\n\tValidationResult,\n} from \"./types.ts\";\nimport { isArrayInput, isLiteralInput, isObjectInput } from \"./types.ts\";\nimport { LRUCache } from \"./utils\";\n\n// ─── Typebars ────────────────────────────────────────────────────────────────\n// Public entry point of the template engine. Orchestrates three phases:\n//\n// 1. **Parsing** — transforms the template string into an AST (via Handlebars)\n// 2. **Analysis** — static validation + return type inference\n// 3. **Execution** — renders the template with real data\n//\n// ─── Architecture v2 ─────────────────────────────────────────────────────────\n// - **LRU cache** for parsed ASTs and compiled Handlebars templates\n// - **Isolated Handlebars environment** per instance (custom helpers)\n// - **`compile()` pattern**: parse-once / execute-many\n// - **`validate()` method**: API shortcut without `outputSchema`\n// - **`registerHelper()`**: custom helpers with static typing\n// - **`ExecuteOptions`**: options object for `execute()`\n//\n// ─── Template Identifiers ────────────────────────────────────────────────────\n// The `{{key:N}}` syntax allows referencing variables from specific data\n// sources, identified by an integer N.\n//\n// - `identifierSchemas`: mapping `{ [id]: JSONSchema7 }` for static analysis\n// - `identifierData`: mapping `{ [id]: Record<string, unknown> }` for execution\n//\n// Usage:\n// engine.execute(\"{{meetingId:1}}\", data, { identifierData: { 1: node1Data } });\n// engine.analyze(\"{{meetingId:1}}\", schema, { identifierSchemas: { 1: node1Schema } });\n\n// ─── Direct Execution Helper Names ───────────────────────────────────────────\n// Helpers whose return values are non-primitive (arrays, objects) and must be\n// wrapped when registered with Handlebars so that mixed/block templates get a\n// human-readable string (e.g. `\", \"` joined) instead of JS default toString().\n// In single-expression mode the executor bypasses Handlebars entirely, so the\n// raw value is preserved.\nconst DIRECT_EXECUTION_HELPER_NAMES = new Set<string>([\n\tArrayHelpers.ARRAY_HELPER_NAME,\n\tMapHelpers.MAP_HELPER_NAME,\n]);\n\n/**\n * Converts a value to a string suitable for embedding in a Handlebars template.\n *\n * - Arrays of primitives are joined with `\", \"`\n * - Arrays of objects are JSON-stringified per element, then joined\n * - Primitives use `String(value)`\n * - null/undefined become `\"\"`\n */\nfunction stringifyForTemplate(value: unknown): string {\n\tif (value === null || value === undefined) return \"\";\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.map((item) => {\n\t\t\t\tif (item === null || item === undefined) return \"\";\n\t\t\t\tif (typeof item === \"object\") return JSON.stringify(item);\n\t\t\t\treturn String(item);\n\t\t\t})\n\t\t\t.join(\", \");\n\t}\n\treturn String(value);\n}\n\n// ─── Main Class ──────────────────────────────────────────────────────────────\n\nexport class Typebars {\n\t/** Isolated Handlebars environment — each engine has its own helpers */\n\tprivate readonly hbs: typeof Handlebars;\n\n\t/** LRU cache of parsed ASTs (avoids re-parsing) */\n\tprivate readonly astCache: LRUCache<string, hbs.AST.Program>;\n\n\t/** LRU cache of compiled Handlebars templates (avoids recompilation) */\n\tprivate readonly compilationCache: LRUCache<\n\t\tstring,\n\t\tHandlebarsTemplateDelegate\n\t>;\n\n\t/** Custom helpers registered on this instance */\n\tprivate readonly helpers = new Map<string, HelperDefinition>();\n\n\tconstructor(options: TemplateEngineOptions = {}) {\n\t\tthis.hbs = Handlebars.create();\n\t\tthis.astCache = new LRUCache(options.astCacheSize ?? 256);\n\t\tthis.compilationCache = new LRUCache(options.compilationCacheSize ?? 256);\n\n\t\t// ── Built-in helpers ─────────────────────────────────────────────\n\t\tnew ArrayHelpers().register(this);\n\t\tnew MathHelpers().register(this);\n\t\tnew LogicalHelpers().register(this);\n\t\tnew MapHelpers().register(this);\n\t\tnew DefaultHelpers().register(this);\n\n\t\t// ── Custom helpers via options ───────────────────────────────────\n\t\tif (options.helpers) {\n\t\t\tfor (const helper of options.helpers) {\n\t\t\t\tconst { name, ...definition } = helper;\n\t\t\t\tthis.registerHelper(name, definition);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Compilation ───────────────────────────────────────────────────────\n\n\t/**\n\t * Compiles a template and returns a `CompiledTemplate` ready to be\n\t * executed or analyzed without re-parsing.\n\t *\n\t * Accepts a `TemplateInput`: string, number, boolean, null, or object.\n\t * For objects, each property is compiled recursively.\n\t *\n\t * @param template - The template to compile\n\t * @returns A reusable `CompiledTemplate`\n\t */\n\tcompile(template: TemplateInput): CompiledTemplate {\n\t\tif (isArrayInput(template)) {\n\t\t\tconst children: CompiledTemplate[] = [];\n\t\t\tfor (const element of template) {\n\t\t\t\tchildren.push(this.compile(element));\n\t\t\t}\n\t\t\treturn CompiledTemplate.fromArray(children, {\n\t\t\t\thelpers: this.helpers,\n\t\t\t\thbs: this.hbs,\n\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t});\n\t\t}\n\t\tif (isObjectInput(template)) {\n\t\t\tconst children: Record<string, CompiledTemplate> = {};\n\t\t\tfor (const [key, value] of Object.entries(template)) {\n\t\t\t\tchildren[key] = this.compile(value);\n\t\t\t}\n\t\t\treturn CompiledTemplate.fromObject(children, {\n\t\t\t\thelpers: this.helpers,\n\t\t\t\thbs: this.hbs,\n\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t});\n\t\t}\n\t\tif (isLiteralInput(template)) {\n\t\t\treturn CompiledTemplate.fromLiteral(template, {\n\t\t\t\thelpers: this.helpers,\n\t\t\t\thbs: this.hbs,\n\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t});\n\t\t}\n\t\tconst ast = this.getCachedAst(template);\n\t\tconst options: CompiledTemplateOptions = {\n\t\t\thelpers: this.helpers,\n\t\t\thbs: this.hbs,\n\t\t\tcompilationCache: this.compilationCache,\n\t\t};\n\t\treturn CompiledTemplate.fromTemplate(ast, template, options);\n\t}\n\n\t// ─── Static Analysis ─────────────────────────────────────────────────────\n\n\t/**\n\t * Statically analyzes a template against a JSON Schema v7 describing\n\t * the available context.\n\t *\n\t * Accepts a `TemplateInput`: string, number, boolean, null, or object.\n\t * For objects, each property is analyzed recursively and the\n\t * `outputSchema` reflects the object structure with resolved types.\n\t *\n\t * @param template - The template to analyze\n\t * @param inputSchema - JSON Schema v7 describing the available variables\n\t * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n\t */\n\tanalyze(\n\t\ttemplate: TemplateInput,\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): AnalysisResult {\n\t\treturn dispatchAnalyze(\n\t\t\ttemplate,\n\t\t\toptions,\n\t\t\t// String handler — parse with cache and analyze the AST\n\t\t\t(tpl, coerceSchema) => {\n\t\t\t\tconst ast = this.getCachedAst(tpl);\n\t\t\t\treturn analyzeFromAst(ast, tpl, inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t});\n\t\t\t},\n\t\t\t// Recursive handler — re-enter analyze() for child elements\n\t\t\t(child, childOptions) => this.analyze(child, inputSchema, childOptions),\n\t\t);\n\t}\n\n\t// ─── Validation ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Validates a template against a schema without returning the output type.\n\t *\n\t * This is an API shortcut for `analyze()` that only returns `valid` and\n\t * `diagnostics`, without `outputSchema`. The full analysis (including type\n\t * inference) is executed internally — this method provides no performance\n\t * gain, only a simplified API.\n\t *\n\t * @param template - The template to validate\n\t * @param inputSchema - JSON Schema v7 describing the available variables\n\t * @param identifierSchemas - (optional) Schemas by identifier\n\t */\n\tvalidate(\n\t\ttemplate: TemplateInput,\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): ValidationResult {\n\t\tconst analysis = this.analyze(template, inputSchema, options);\n\t\treturn {\n\t\t\tvalid: analysis.valid,\n\t\t\tdiagnostics: analysis.diagnostics,\n\t\t};\n\t}\n\n\t// ─── Syntax Validation ───────────────────────────────────────────────────\n\n\t/**\n\t * Checks only that the template syntax is valid (parsing).\n\t * Does not require a schema — useful for quick feedback in an editor.\n\t *\n\t * For objects, recursively checks each property.\n\t *\n\t * @param template - The template to validate\n\t * @returns `true` if the template is syntactically correct\n\t */\n\tisValidSyntax(template: TemplateInput): boolean {\n\t\tif (isArrayInput(template)) {\n\t\t\treturn template.every((v) => this.isValidSyntax(v));\n\t\t}\n\t\tif (isObjectInput(template)) {\n\t\t\treturn Object.values(template).every((v) => this.isValidSyntax(v));\n\t\t}\n\t\tif (isLiteralInput(template)) return true;\n\t\ttry {\n\t\t\tthis.getCachedAst(template);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// ─── Execution ───────────────────────────────────────────────────────────\n\n\t/**\n\t * Executes a template with the provided data.\n\t *\n\t * Accepts a `TemplateInput`: string, number, boolean, null, or object.\n\t * For objects, each property is executed recursively and an object with\n\t * resolved values is returned.\n\t *\n\t * If a `schema` is provided in options, static analysis is performed\n\t * before execution. A `TemplateAnalysisError` is thrown on errors.\n\t *\n\t * @param template - The template to execute\n\t * @param data - The context data for rendering\n\t * @param options - Execution options (schema, identifierData, identifierSchemas)\n\t * @returns The execution result\n\t */\n\texecute(\n\t\ttemplate: TemplateInput,\n\t\tdata?: TemplateData,\n\t\toptions?: ExecuteOptions,\n\t): unknown {\n\t\treturn dispatchExecute(\n\t\t\ttemplate,\n\t\t\toptions,\n\t\t\t// String handler — parse, optionally validate, then execute\n\t\t\t(tpl, coerceSchema) => {\n\t\t\t\tconst ast = this.getCachedAst(tpl);\n\n\t\t\t\t// Pre-execution static validation if a schema is provided\n\t\t\t\tif (options?.schema) {\n\t\t\t\t\tconst analysis = analyzeFromAst(ast, tpl, options.schema, {\n\t\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t\t});\n\t\t\t\t\tif (!analysis.valid) {\n\t\t\t\t\t\tthrow new TemplateAnalysisError(analysis.diagnostics);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn executeFromAst(ast, tpl, data, {\n\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\thbs: this.hbs,\n\t\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t});\n\t\t\t},\n\t\t\t// Recursive handler — re-enter execute() for child elements\n\t\t\t(child, childOptions) =>\n\t\t\t\tthis.execute(child, data, { ...options, ...childOptions }),\n\t\t);\n\t}\n\n\t// ─── Combined Shortcuts ──────────────────────────────────────────────────\n\n\t/**\n\t * Analyzes a template and, if valid, executes it with the provided data.\n\t * Returns both the analysis result and the executed value.\n\t *\n\t * For objects, each property is analyzed and executed recursively.\n\t * The entire object is considered invalid if at least one property is.\n\t *\n\t * @param template - The template\n\t * @param inputSchema - JSON Schema v7 describing the available variables\n\t * @param data - The context data for rendering\n\t * @param options - (optional) Options for template identifiers\n\t * @returns An object `{ analysis, value }` where `value` is `undefined`\n\t * if analysis failed.\n\t */\n\tanalyzeAndExecute(\n\t\ttemplate: TemplateInput,\n\t\tinputSchema: JSONSchema7 = {},\n\t\tdata: TemplateData,\n\t\toptions?: AnalyzeAndExecuteOptions,\n\t): { analysis: AnalysisResult; value: unknown } {\n\t\treturn dispatchAnalyzeAndExecute(\n\t\t\ttemplate,\n\t\t\toptions,\n\t\t\t// String handler — analyze then execute if valid\n\t\t\t(tpl, coerceSchema) => {\n\t\t\t\tconst ast = this.getCachedAst(tpl);\n\t\t\t\tconst analysis = analyzeFromAst(ast, tpl, inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t});\n\n\t\t\t\tif (!analysis.valid) {\n\t\t\t\t\treturn { analysis, value: undefined };\n\t\t\t\t}\n\n\t\t\t\tconst value = executeFromAst(ast, tpl, data, {\n\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\thbs: this.hbs,\n\t\t\t\t\tcompilationCache: this.compilationCache,\n\t\t\t\t\tcoerceSchema,\n\t\t\t\t\thelpers: this.helpers,\n\t\t\t\t});\n\t\t\t\treturn { analysis, value };\n\t\t\t},\n\t\t\t// Recursive handler — re-enter analyzeAndExecute() for child elements\n\t\t\t(child, childOptions) =>\n\t\t\t\tthis.analyzeAndExecute(child, inputSchema, data, childOptions),\n\t\t);\n\t}\n\n\t// ─── Custom Helper Management ──────────────────────────────────────────\n\n\t/**\n\t * Registers a custom helper on this engine instance.\n\t *\n\t * The helper is available for both execution (via Handlebars) and\n\t * static analysis (via its declared `returnType`).\n\t *\n\t * @param name - Helper name (e.g. `\"uppercase\"`)\n\t * @param definition - Helper definition (implementation + return type)\n\t * @returns `this` to allow chaining\n\t */\n\tregisterHelper(name: string, definition: HelperDefinition): this {\n\t\tthis.helpers.set(name, definition);\n\n\t\t// For helpers that return non-primitive values (arrays, objects),\n\t\t// register a Handlebars-friendly wrapper that converts the result\n\t\t// to a string. In single-expression mode the executor bypasses\n\t\t// Handlebars entirely (via tryDirectHelperExecution) and returns\n\t\t// the raw value, so this wrapper only affects mixed/block templates\n\t\t// where Handlebars renders the result into a larger string.\n\t\tif (DIRECT_EXECUTION_HELPER_NAMES.has(name)) {\n\t\t\tthis.hbs.registerHelper(name, (...args: unknown[]) => {\n\t\t\t\t// Handlebars appends an `options` object as the last argument.\n\t\t\t\t// Strip it before calling the real fn.\n\t\t\t\tconst hbsArgs = args.slice(0, -1);\n\t\t\t\tconst raw = definition.fn(...hbsArgs);\n\t\t\t\treturn stringifyForTemplate(raw);\n\t\t\t});\n\t\t} else {\n\t\t\tthis.hbs.registerHelper(name, definition.fn);\n\t\t}\n\n\t\t// Invalidate the compilation cache because helpers have changed\n\t\tthis.compilationCache.clear();\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes a custom helper from this engine instance.\n\t *\n\t * @param name - Name of the helper to remove\n\t * @returns `this` to allow chaining\n\t */\n\tunregisterHelper(name: string): this {\n\t\tthis.helpers.delete(name);\n\t\tthis.hbs.unregisterHelper(name);\n\n\t\t// Invalidate the compilation cache\n\t\tthis.compilationCache.clear();\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Checks whether a helper is registered on this instance.\n\t *\n\t * @param name - Helper name\n\t * @returns `true` if the helper is registered\n\t */\n\thasHelper(name: string): boolean {\n\t\treturn this.helpers.has(name);\n\t}\n\n\t// ─── Cache Management ──────────────────────────────────────────────────\n\n\t/**\n\t * Clears all internal caches (AST + compilation).\n\t *\n\t * Useful after a configuration change or to free memory.\n\t */\n\tclearCaches(): void {\n\t\tthis.astCache.clear();\n\t\tthis.compilationCache.clear();\n\t}\n\n\t// ─── Internals ─────────────────────────────────────────────────────────\n\n\t/**\n\t * Retrieves the AST of a template from the cache, or parses and caches it.\n\t */\n\tprivate getCachedAst(template: string): hbs.AST.Program {\n\t\tlet ast = this.astCache.get(template);\n\t\tif (!ast) {\n\t\t\tast = parse(template);\n\t\t\tthis.astCache.set(template, ast);\n\t\t}\n\t\treturn ast;\n\t}\n}\n"],"names":["Handlebars","analyzeFromAst","CompiledTemplate","dispatchAnalyze","dispatchAnalyzeAndExecute","dispatchExecute","TemplateAnalysisError","executeFromAst","ArrayHelpers","DefaultHelpers","LogicalHelpers","MapHelpers","MathHelpers","parse","isArrayInput","isLiteralInput","isObjectInput","LRUCache","DIRECT_EXECUTION_HELPER_NAMES","Set","ARRAY_HELPER_NAME","MAP_HELPER_NAME","stringifyForTemplate","value","undefined","Array","isArray","map","item","JSON","stringify","String","join","Typebars","compile","template","children","element","push","fromArray","helpers","hbs","compilationCache","key","Object","entries","fromObject","fromLiteral","ast","getCachedAst","options","fromTemplate","analyze","inputSchema","tpl","coerceSchema","identifierSchemas","child","childOptions","validate","analysis","valid","diagnostics","isValidSyntax","every","v","values","execute","data","schema","identifierData","analyzeAndExecute","registerHelper","name","definition","set","has","args","hbsArgs","slice","raw","fn","clear","unregisterHelper","delete","hasHelper","clearCaches","astCache","get","Map","create","astCacheSize","compilationCacheSize","register","helper"],"mappings":"oLAAA,OAAOA,eAAgB,YAAa,AAGpC,QAASC,cAAc,KAAQ,eAAgB,AAC/C,QACCC,gBAAgB,KAEV,wBAAyB,AAChC,QACCC,eAAe,CACfC,yBAAyB,CACzBC,eAAe,KACT,eAAgB,AACvB,QAASC,qBAAqB,KAAQ,aAAc,AACpD,QAASC,cAAc,KAAQ,eAAgB,AAC/C,QACCC,YAAY,CACZC,cAAc,CACdC,cAAc,CACdC,UAAU,CACVC,WAAW,KACL,oBAAqB,AAC5B,QAASC,KAAK,KAAQ,aAAc,AAWpC,QAASC,YAAY,CAAEC,cAAc,CAAEC,aAAa,KAAQ,YAAa,AACzE,QAASC,QAAQ,KAAQ,SAAU,CAkCnC,MAAMC,8BAAgC,IAAIC,IAAY,CACrDX,aAAaY,iBAAiB,CAC9BT,WAAWU,eAAe,CAC1B,EAUD,SAASC,qBAAqBC,KAAc,EAC3C,GAAIA,QAAU,MAAQA,QAAUC,UAAW,MAAO,GAClD,GAAIC,MAAMC,OAAO,CAACH,OAAQ,CACzB,OAAOA,MACLI,GAAG,CAAC,AAACC,OACL,GAAIA,OAAS,MA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