typebars 1.0.22 → 1.0.24

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/compiled-template.ts"],"sourcesContent":["import type Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type { AnalyzeOptions } from \"./analyzer.ts\";\nimport { analyzeFromAst } from \"./analyzer.ts\";\nimport { resolveChildCoerceSchema, shouldExcludeEntry } from \"./dispatch.ts\";\nimport { TemplateAnalysisError } from \"./errors.ts\";\nimport { type ExecutorContext, executeFromAst } from \"./executor.ts\";\nimport type {\n\tAnalysisResult,\n\tExecuteOptions,\n\tHelperDefinition,\n\tTemplateData,\n\tValidationResult,\n} from \"./types.ts\";\nimport { inferPrimitiveSchema } from \"./types.ts\";\nimport {\n\taggregateArrayAnalysis,\n\taggregateArrayAnalysisAndExecution,\n\taggregateObjectAnalysis,\n\taggregateObjectAnalysisAndExecution,\n\ttype LRUCache,\n} from \"./utils\";\n\n// ─── CompiledTemplate ────────────────────────────────────────────────────────\n// Pre-parsed template ready to be executed or analyzed without re-parsing.\n//\n// The compile-once / execute-many pattern avoids the cost of Handlebars\n// parsing on every call. The AST is parsed once at compile time, and the\n// Handlebars template is lazily compiled on the first `execute()`.\n//\n// Usage:\n// const tpl = engine.compile(\"Hello {{name}}\");\n// tpl.execute({ name: \"Alice\" }); // no re-parsing\n// tpl.execute({ name: \"Bob\" }); // no re-parsing or recompilation\n// tpl.analyze(schema); // no re-parsing\n//\n// ─── Internal State (TemplateState) ──────────────────────────────────────────\n// CompiledTemplate operates in 4 exclusive modes, modeled by a discriminated\n// union `TemplateState`:\n//\n// - `\"template\"` — parsed Handlebars template (AST + source string)\n// - `\"literal\"` — primitive passthrough value (number, boolean, null)\n// - `\"object\"` — object where each property is a child CompiledTemplate\n// - `\"array\"` — array where each element is a child CompiledTemplate\n//\n// This design eliminates optional fields and `!` assertions in favor of\n// natural TypeScript narrowing via `switch (this.state.kind)`.\n//\n// ─── Advantages Over the Direct API ──────────────────────────────────────────\n// - **Performance**: parsing and compilation happen only once\n// - **Simplified API**: no need to re-pass the template string on each call\n// - **Consistency**: the same AST is used for both analysis and execution\n\n// ─── Internal Types ──────────────────────────────────────────────────────────\n\n/** Internal options passed by Typebars during compilation */\nexport interface CompiledTemplateOptions {\n\t/** Custom helpers registered on the engine */\n\thelpers: Map<string, HelperDefinition>;\n\t/** Isolated Handlebars environment (with registered helpers) */\n\thbs: typeof Handlebars;\n\t/** Compilation cache shared by the engine */\n\tcompilationCache: LRUCache<string, HandlebarsTemplateDelegate>;\n}\n\n/** Discriminated internal state of the CompiledTemplate */\ntype TemplateState =\n\t| {\n\t\t\treadonly kind: \"template\";\n\t\t\treadonly ast: hbs.AST.Program;\n\t\t\treadonly source: string;\n\t }\n\t| { readonly kind: \"literal\"; readonly value: number | boolean | null }\n\t| {\n\t\t\treadonly kind: \"object\";\n\t\t\treadonly children: Record<string, CompiledTemplate>;\n\t }\n\t| {\n\t\t\treadonly kind: \"array\";\n\t\t\treadonly elements: CompiledTemplate[];\n\t };\n\n// ─── Public Class ────────────────────────────────────────────────────────────\n\nexport class CompiledTemplate {\n\t/** Discriminated internal state */\n\tprivate readonly state: TemplateState;\n\n\t/** Options inherited from the parent Typebars instance */\n\tprivate readonly options: CompiledTemplateOptions;\n\n\t/** Compiled Handlebars template (lazy — created on the first `execute()` that needs it) */\n\tprivate hbsCompiled: HandlebarsTemplateDelegate | null = null;\n\n\t// ─── Public Accessors (backward-compatible) ──────────────────────────\n\n\t/** The pre-parsed Handlebars AST — `null` in literal, object, or array mode */\n\tget ast(): hbs.AST.Program | null {\n\t\treturn this.state.kind === \"template\" ? this.state.ast : null;\n\t}\n\n\t/** The original template source — empty string in literal, object, or array mode */\n\tget template(): string {\n\t\treturn this.state.kind === \"template\" ? this.state.source : \"\";\n\t}\n\n\t// ─── Construction ────────────────────────────────────────────────────\n\n\tprivate constructor(state: TemplateState, options: CompiledTemplateOptions) {\n\t\tthis.state = state;\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate for a parsed Handlebars template.\n\t *\n\t * @param ast - The pre-parsed Handlebars AST\n\t * @param source - The original template source\n\t * @param options - Options inherited from Typebars\n\t */\n\tstatic fromTemplate(\n\t\tast: hbs.AST.Program,\n\t\tsource: string,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"template\", ast, source }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in passthrough mode for a literal value\n\t * (number, boolean, null). No parsing or compilation is performed.\n\t *\n\t * @param value - The primitive value\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that always returns `value`\n\t */\n\tstatic fromLiteral(\n\t\tvalue: number | boolean | null,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"literal\", value }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in object mode, where each property is a\n\t * child CompiledTemplate. All operations are recursively delegated\n\t * to the children.\n\t *\n\t * @param children - The compiled child templates `{ [key]: CompiledTemplate }`\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that delegates to children\n\t */\n\tstatic fromObject(\n\t\tchildren: Record<string, CompiledTemplate>,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"object\", children }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in array mode, where each element is a\n\t * child CompiledTemplate. All operations are recursively delegated\n\t * to the elements.\n\t *\n\t * @param elements - The compiled child templates (ordered array)\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that delegates to elements\n\t */\n\tstatic fromArray(\n\t\telements: CompiledTemplate[],\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"array\", elements }, options);\n\t}\n\n\t// ─── Static Analysis ─────────────────────────────────────────────────\n\n\t/**\n\t * Statically analyzes this template against a JSON Schema v7.\n\t *\n\t * Returns an `AnalysisResult` containing:\n\t * - `valid` — `true` if no errors\n\t * - `diagnostics` — list of diagnostics (errors + warnings)\n\t * - `outputSchema` — JSON Schema describing the return type\n\t *\n\t * Since the AST is pre-parsed, this method never re-parses the template.\n\t *\n\t * @param inputSchema - JSON Schema describing the available variables\n\t * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n\t */\n\tanalyze(\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): AnalysisResult {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"array\": {\n\t\t\t\tconst { elements } = this.state;\n\n\t\t\t\tif (exclude) {\n\t\t\t\t\t// When excludeTemplateExpression is enabled, filter out elements\n\t\t\t\t\t// that are string templates containing Handlebars expressions.\n\t\t\t\t\tconst kept = elements.filter(\n\t\t\t\t\t\t(el) => !isCompiledTemplateWithExpression(el),\n\t\t\t\t\t);\n\t\t\t\t\treturn aggregateArrayAnalysis(kept.length, (index) => {\n\t\t\t\t\t\tconst element = kept[index];\n\t\t\t\t\t\tif (!element)\n\t\t\t\t\t\t\tthrow new Error(`unreachable: missing element at index ${index}`);\n\t\t\t\t\t\treturn element.analyze(inputSchema, options);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn aggregateArrayAnalysis(elements.length, (index) => {\n\t\t\t\t\tconst element = elements[index];\n\t\t\t\t\tif (!element)\n\t\t\t\t\t\tthrow new Error(`unreachable: missing element at index ${index}`);\n\t\t\t\t\treturn element.analyze(inputSchema, options);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\tconst coerceSchema = options?.coerceSchema;\n\n\t\t\t\t// When excludeTemplateExpression is enabled, filter out keys whose\n\t\t\t\t// compiled children are string templates with Handlebars expressions.\n\t\t\t\tconst keys = exclude\n\t\t\t\t\t? Object.keys(children).filter((key) => {\n\t\t\t\t\t\t\tconst child = children[key];\n\t\t\t\t\t\t\treturn !child || !isCompiledTemplateWithExpression(child);\n\t\t\t\t\t\t})\n\t\t\t\t\t: Object.keys(children);\n\n\t\t\t\treturn aggregateObjectAnalysis(keys, (key) => {\n\t\t\t\t\tconst child = children[key];\n\t\t\t\t\tif (!child) throw new Error(`unreachable: missing child \"${key}\"`);\n\t\t\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\t\t\treturn child.analyze(inputSchema, {\n\t\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn {\n\t\t\t\t\tvalid: true,\n\t\t\t\t\tdiagnostics: [],\n\t\t\t\t\toutputSchema: inferPrimitiveSchema(this.state.value),\n\t\t\t\t};\n\n\t\t\tcase \"template\":\n\t\t\t\treturn analyzeFromAst(this.state.ast, this.state.source, inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\thelpers: this.options.helpers,\n\t\t\t\t\tcoerceSchema: options?.coerceSchema,\n\t\t\t\t});\n\t\t}\n\t}\n\n\t// ─── Validation ──────────────────────────────────────────────────────\n\n\t/**\n\t * Validates the 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 inputSchema - JSON Schema describing the available variables\n\t * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n\t */\n\tvalidate(\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): ValidationResult {\n\t\tconst analysis = this.analyze(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// ─── Execution ───────────────────────────────────────────────────────\n\n\t/**\n\t * Executes this template with the provided data.\n\t *\n\t * The return type depends on the template structure:\n\t * - Single expression `{{expr}}` → raw value (number, boolean, object…)\n\t * - Mixed template or with blocks → `string`\n\t * - Primitive literal → the value as-is\n\t * - Object template → object with resolved values\n\t * - Array template → array with resolved values\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 data - The context data for rendering\n\t * @param options - Execution options (schema, identifierData, coerceSchema, etc.)\n\t * @returns The execution result\n\t */\n\texecute(data: TemplateData, options?: ExecuteOptions): unknown {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"array\": {\n\t\t\t\tconst { elements } = this.state;\n\t\t\t\tconst effective = exclude\n\t\t\t\t\t? elements.filter((el) => !isCompiledTemplateWithExpression(el))\n\t\t\t\t\t: elements;\n\t\t\t\tconst result: unknown[] = [];\n\t\t\t\tfor (const element of effective) {\n\t\t\t\t\tresult.push(element.execute(data, options));\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\tconst coerceSchema = options?.coerceSchema;\n\t\t\t\tconst keys = exclude\n\t\t\t\t\t? Object.keys(children).filter((key) => {\n\t\t\t\t\t\t\tconst child = children[key];\n\t\t\t\t\t\t\treturn !child || !isCompiledTemplateWithExpression(child);\n\t\t\t\t\t\t})\n\t\t\t\t\t: Object.keys(children);\n\t\t\t\tconst result: Record<string, unknown> = {};\n\t\t\t\tfor (const key of keys) {\n\t\t\t\t\tconst child = children[key];\n\t\t\t\t\tif (!child) continue;\n\t\t\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\t\t\tresult[key] = child.execute(data, {\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn this.state.value;\n\n\t\t\tcase \"template\": {\n\t\t\t\t// When excludeTemplateExpression is enabled at root level,\n\t\t\t\t// return null if the template contains Handlebars expressions\n\t\t\t\t// (there is no parent to remove it from).\n\t\t\t\tif (exclude && isCompiledTemplateWithExpression(this)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\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 = this.analyze(options.schema, {\n\t\t\t\t\t\tidentifierSchemas: options.identifierSchemas,\n\t\t\t\t\t\tcoerceSchema: options.coerceSchema,\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(\n\t\t\t\t\tthis.state.ast,\n\t\t\t\t\tthis.state.source,\n\t\t\t\t\tdata,\n\t\t\t\t\tthis.buildExecutorContext(options),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Combined Shortcuts ──────────────────────────────────────────────\n\n\t/**\n\t * Analyzes and executes the template in a single call.\n\t *\n\t * Returns both the analysis result and the executed value.\n\t * If analysis fails, `value` is `undefined`.\n\t *\n\t * @param inputSchema - JSON Schema describing the available variables\n\t * @param data - The context data for rendering\n\t * @param options - Additional options (identifierSchemas, identifierData, coerceSchema)\n\t * @returns `{ analysis, value }`\n\t */\n\tanalyzeAndExecute(\n\t\tinputSchema: JSONSchema7 = {},\n\t\tdata: TemplateData,\n\t\toptions?: {\n\t\t\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t\t\tidentifierData?: Record<number, Record<string, unknown>>;\n\t\t\tcoerceSchema?: JSONSchema7;\n\t\t},\n\t): { analysis: AnalysisResult; value: unknown } {\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"array\": {\n\t\t\t\tconst { elements } = this.state;\n\t\t\t\treturn aggregateArrayAnalysisAndExecution(elements.length, (index) => {\n\t\t\t\t\tconst element = elements[index];\n\t\t\t\t\tif (!element)\n\t\t\t\t\t\tthrow new Error(`unreachable: missing element at index ${index}`);\n\t\t\t\t\treturn element.analyzeAndExecute(inputSchema, data, options);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\tconst coerceSchema = options?.coerceSchema;\n\t\t\t\treturn aggregateObjectAnalysisAndExecution(\n\t\t\t\t\tObject.keys(children),\n\t\t\t\t\t(key) => {\n\t\t\t\t\t\tconst child = children[key];\n\t\t\t\t\t\tif (!child) throw new Error(`unreachable: missing child \"${key}\"`);\n\t\t\t\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(\n\t\t\t\t\t\t\tcoerceSchema,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn child.analyzeAndExecute(inputSchema, data, {\n\t\t\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn {\n\t\t\t\t\tanalysis: {\n\t\t\t\t\t\tvalid: true,\n\t\t\t\t\t\tdiagnostics: [],\n\t\t\t\t\t\toutputSchema: inferPrimitiveSchema(this.state.value),\n\t\t\t\t\t},\n\t\t\t\t\tvalue: this.state.value,\n\t\t\t\t};\n\n\t\t\tcase \"template\": {\n\t\t\t\tconst analysis = this.analyze(inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\tcoerceSchema: options?.coerceSchema,\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(\n\t\t\t\t\tthis.state.ast,\n\t\t\t\t\tthis.state.source,\n\t\t\t\t\tdata,\n\t\t\t\t\tthis.buildExecutorContext({\n\t\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\t\tcoerceSchema: options?.coerceSchema,\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\treturn { analysis, value };\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Internals ───────────────────────────────────────────────────────\n\n\t/**\n\t * Builds the execution context for `executeFromAst`.\n\t *\n\t * Uses lazy Handlebars compilation: the template is only compiled\n\t * on the first call that needs it (not for single expressions).\n\t */\n\tprivate buildExecutorContext(options?: ExecuteOptions): ExecutorContext {\n\t\treturn {\n\t\t\tidentifierData: options?.identifierData,\n\t\t\tcompiledTemplate: this.getOrCompileHbs(),\n\t\t\thbs: this.options.hbs,\n\t\t\tcompilationCache: this.options.compilationCache,\n\t\t\tcoerceSchema: options?.coerceSchema,\n\t\t\thelpers: this.options.helpers,\n\t\t};\n\t}\n\n\t/**\n\t * Lazily compiles the Handlebars template and caches it.\n\t *\n\t * Compilation happens only once — subsequent calls return the\n\t * in-memory compiled template.\n\t *\n\t * Precondition: this method is only called from \"template\" mode.\n\t */\n\tprivate getOrCompileHbs(): HandlebarsTemplateDelegate {\n\t\tif (!this.hbsCompiled) {\n\t\t\t// In \"template\" mode, `this.template` returns the source string\n\t\t\tthis.hbsCompiled = this.options.hbs.compile(this.template, {\n\t\t\t\tnoEscape: true,\n\t\t\t\tstrict: false,\n\t\t\t});\n\t\t}\n\t\treturn this.hbsCompiled;\n\t}\n}\n\n// ─── Internal Helpers ────────────────────────────────────────────────────────\n\n/**\n * Determines whether a `CompiledTemplate` represents a string template\n * containing Handlebars expressions (`{{…}}`).\n *\n * Used by `excludeTemplateExpression` filtering to skip dynamic entries\n * in object and array modes.\n */\nfunction isCompiledTemplateWithExpression(ct: CompiledTemplate): boolean {\n\t// Only \"template\" kind can contain expressions. Literals, objects,\n\t// and arrays are never excluded at the entry level — objects and\n\t// arrays are recursively filtered by the analysis method itself.\n\treturn ct.template !== \"\" && shouldExcludeEntry(ct.template);\n}\n"],"names":["CompiledTemplate","ast","state","kind","template","source","fromTemplate","options","fromLiteral","value","fromObject","children","fromArray","elements","analyze","inputSchema","exclude","excludeTemplateExpression","kept","filter","el","isCompiledTemplateWithExpression","aggregateArrayAnalysis","length","index","element","Error","coerceSchema","keys","Object","key","child","aggregateObjectAnalysis","childCoerceSchema","resolveChildCoerceSchema","identifierSchemas","valid","diagnostics","outputSchema","inferPrimitiveSchema","analyzeFromAst","helpers","validate","analysis","execute","data","effective","result","push","schema","TemplateAnalysisError","executeFromAst","buildExecutorContext","analyzeAndExecute","aggregateArrayAnalysisAndExecution","aggregateObjectAnalysisAndExecution","identifierData","undefined","compiledTemplate","getOrCompileHbs","hbs","compilationCache","hbsCompiled","compile","noEscape","strict","ct","shouldExcludeEntry"],"mappings":"oGAoFaA,0DAAAA,8CAjFkB,2CAC8B,yCACvB,yCACe,wCAQhB,mCAO9B,+LA+DA,MAAMA,iBAaZ,IAAIC,KAA8B,CACjC,OAAO,IAAI,CAACC,KAAK,CAACC,IAAI,GAAK,WAAa,IAAI,CAACD,KAAK,CAACD,GAAG,CAAG,IAC1D,CAGA,IAAIG,UAAmB,CACtB,OAAO,IAAI,CAACF,KAAK,CAACC,IAAI,GAAK,WAAa,IAAI,CAACD,KAAK,CAACG,MAAM,CAAG,EAC7D,CAgBA,OAAOC,aACNL,GAAoB,CACpBI,MAAc,CACdE,OAAgC,CACb,CACnB,OAAO,IAAIP,iBAAiB,CAAEG,KAAM,WAAYF,IAAKI,MAAO,EAAGE,QAChE,CAUA,OAAOC,YACNC,KAA8B,CAC9BF,OAAgC,CACb,CACnB,O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K,OAAO,CAAGA,OAChB,CAuYD,CAWA,SAASc,iCAAiC6C,EAAoB,EAI7D,OAAOA,GAAG9D,QAAQ,GAAK,IAAM+D,GAAAA,8BAAkB,EAACD,GAAG9D,QAAQ,CAC5D"}
1
+ {"version":3,"sources":["../../src/compiled-template.ts"],"sourcesContent":["import type Handlebars from \"handlebars\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type { AnalyzeOptions } from \"./analyzer.ts\";\nimport { analyzeFromAst } from \"./analyzer.ts\";\nimport { resolveChildCoerceSchema, shouldExcludeEntry } from \"./dispatch.ts\";\nimport { TemplateAnalysisError } from \"./errors.ts\";\nimport { type ExecutorContext, executeFromAst } from \"./executor.ts\";\nimport type {\n\tAnalysisResult,\n\tExecuteOptions,\n\tHelperDefinition,\n\tIdentifierData,\n\tTemplateData,\n\tValidationResult,\n} from \"./types.ts\";\nimport { inferPrimitiveSchema } from \"./types.ts\";\nimport {\n\taggregateArrayAnalysis,\n\taggregateArrayAnalysisAndExecution,\n\taggregateObjectAnalysis,\n\taggregateObjectAnalysisAndExecution,\n\ttype LRUCache,\n} from \"./utils\";\n\n// ─── CompiledTemplate ────────────────────────────────────────────────────────\n// Pre-parsed template ready to be executed or analyzed without re-parsing.\n//\n// The compile-once / execute-many pattern avoids the cost of Handlebars\n// parsing on every call. The AST is parsed once at compile time, and the\n// Handlebars template is lazily compiled on the first `execute()`.\n//\n// Usage:\n// const tpl = engine.compile(\"Hello {{name}}\");\n// tpl.execute({ name: \"Alice\" }); // no re-parsing\n// tpl.execute({ name: \"Bob\" }); // no re-parsing or recompilation\n// tpl.analyze(schema); // no re-parsing\n//\n// ─── Internal State (TemplateState) ──────────────────────────────────────────\n// CompiledTemplate operates in 4 exclusive modes, modeled by a discriminated\n// union `TemplateState`:\n//\n// - `\"template\"` — parsed Handlebars template (AST + source string)\n// - `\"literal\"` — primitive passthrough value (number, boolean, null)\n// - `\"object\"` — object where each property is a child CompiledTemplate\n// - `\"array\"` — array where each element is a child CompiledTemplate\n//\n// This design eliminates optional fields and `!` assertions in favor of\n// natural TypeScript narrowing via `switch (this.state.kind)`.\n//\n// ─── Advantages Over the Direct API ──────────────────────────────────────────\n// - **Performance**: parsing and compilation happen only once\n// - **Simplified API**: no need to re-pass the template string on each call\n// - **Consistency**: the same AST is used for both analysis and execution\n\n// ─── Internal Types ──────────────────────────────────────────────────────────\n\n/** Internal options passed by Typebars during compilation */\nexport interface CompiledTemplateOptions {\n\t/** Custom helpers registered on the engine */\n\thelpers: Map<string, HelperDefinition>;\n\t/** Isolated Handlebars environment (with registered helpers) */\n\thbs: typeof Handlebars;\n\t/** Compilation cache shared by the engine */\n\tcompilationCache: LRUCache<string, HandlebarsTemplateDelegate>;\n}\n\n/** Discriminated internal state of the CompiledTemplate */\ntype TemplateState =\n\t| {\n\t\t\treadonly kind: \"template\";\n\t\t\treadonly ast: hbs.AST.Program;\n\t\t\treadonly source: string;\n\t }\n\t| { readonly kind: \"literal\"; readonly value: number | boolean | null }\n\t| {\n\t\t\treadonly kind: \"object\";\n\t\t\treadonly children: Record<string, CompiledTemplate>;\n\t }\n\t| {\n\t\t\treadonly kind: \"array\";\n\t\t\treadonly elements: CompiledTemplate[];\n\t };\n\n// ─── Public Class ────────────────────────────────────────────────────────────\n\nexport class CompiledTemplate {\n\t/** Discriminated internal state */\n\tprivate readonly state: TemplateState;\n\n\t/** Options inherited from the parent Typebars instance */\n\tprivate readonly options: CompiledTemplateOptions;\n\n\t/** Compiled Handlebars template (lazy — created on the first `execute()` that needs it) */\n\tprivate hbsCompiled: HandlebarsTemplateDelegate | null = null;\n\n\t// ─── Public Accessors (backward-compatible) ──────────────────────────\n\n\t/** The pre-parsed Handlebars AST — `null` in literal, object, or array mode */\n\tget ast(): hbs.AST.Program | null {\n\t\treturn this.state.kind === \"template\" ? this.state.ast : null;\n\t}\n\n\t/** The original template source — empty string in literal, object, or array mode */\n\tget template(): string {\n\t\treturn this.state.kind === \"template\" ? this.state.source : \"\";\n\t}\n\n\t// ─── Construction ────────────────────────────────────────────────────\n\n\tprivate constructor(state: TemplateState, options: CompiledTemplateOptions) {\n\t\tthis.state = state;\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate for a parsed Handlebars template.\n\t *\n\t * @param ast - The pre-parsed Handlebars AST\n\t * @param source - The original template source\n\t * @param options - Options inherited from Typebars\n\t */\n\tstatic fromTemplate(\n\t\tast: hbs.AST.Program,\n\t\tsource: string,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"template\", ast, source }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in passthrough mode for a literal value\n\t * (number, boolean, null). No parsing or compilation is performed.\n\t *\n\t * @param value - The primitive value\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that always returns `value`\n\t */\n\tstatic fromLiteral(\n\t\tvalue: number | boolean | null,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"literal\", value }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in object mode, where each property is a\n\t * child CompiledTemplate. All operations are recursively delegated\n\t * to the children.\n\t *\n\t * @param children - The compiled child templates `{ [key]: CompiledTemplate }`\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that delegates to children\n\t */\n\tstatic fromObject(\n\t\tchildren: Record<string, CompiledTemplate>,\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"object\", children }, options);\n\t}\n\n\t/**\n\t * Creates a CompiledTemplate in array mode, where each element is a\n\t * child CompiledTemplate. All operations are recursively delegated\n\t * to the elements.\n\t *\n\t * @param elements - The compiled child templates (ordered array)\n\t * @param options - Options inherited from Typebars\n\t * @returns A CompiledTemplate that delegates to elements\n\t */\n\tstatic fromArray(\n\t\telements: CompiledTemplate[],\n\t\toptions: CompiledTemplateOptions,\n\t): CompiledTemplate {\n\t\treturn new CompiledTemplate({ kind: \"array\", elements }, options);\n\t}\n\n\t// ─── Static Analysis ─────────────────────────────────────────────────\n\n\t/**\n\t * Statically analyzes this template against a JSON Schema v7.\n\t *\n\t * Returns an `AnalysisResult` containing:\n\t * - `valid` — `true` if no errors\n\t * - `diagnostics` — list of diagnostics (errors + warnings)\n\t * - `outputSchema` — JSON Schema describing the return type\n\t *\n\t * Since the AST is pre-parsed, this method never re-parses the template.\n\t *\n\t * @param inputSchema - JSON Schema describing the available variables\n\t * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n\t */\n\tanalyze(\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): AnalysisResult {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"array\": {\n\t\t\t\tconst { elements } = this.state;\n\n\t\t\t\tif (exclude) {\n\t\t\t\t\t// When excludeTemplateExpression is enabled, filter out elements\n\t\t\t\t\t// that are string templates containing Handlebars expressions.\n\t\t\t\t\tconst kept = elements.filter(\n\t\t\t\t\t\t(el) => !isCompiledTemplateWithExpression(el),\n\t\t\t\t\t);\n\t\t\t\t\treturn aggregateArrayAnalysis(kept.length, (index) => {\n\t\t\t\t\t\tconst element = kept[index];\n\t\t\t\t\t\tif (!element)\n\t\t\t\t\t\t\tthrow new Error(`unreachable: missing element at index ${index}`);\n\t\t\t\t\t\treturn element.analyze(inputSchema, options);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn aggregateArrayAnalysis(elements.length, (index) => {\n\t\t\t\t\tconst element = elements[index];\n\t\t\t\t\tif (!element)\n\t\t\t\t\t\tthrow new Error(`unreachable: missing element at index ${index}`);\n\t\t\t\t\treturn element.analyze(inputSchema, options);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\tconst coerceSchema = options?.coerceSchema;\n\n\t\t\t\t// When excludeTemplateExpression is enabled, filter out keys whose\n\t\t\t\t// compiled children are string templates with Handlebars expressions.\n\t\t\t\tconst keys = exclude\n\t\t\t\t\t? Object.keys(children).filter((key) => {\n\t\t\t\t\t\t\tconst child = children[key];\n\t\t\t\t\t\t\treturn !child || !isCompiledTemplateWithExpression(child);\n\t\t\t\t\t\t})\n\t\t\t\t\t: Object.keys(children);\n\n\t\t\t\treturn aggregateObjectAnalysis(keys, (key) => {\n\t\t\t\t\tconst child = children[key];\n\t\t\t\t\tif (!child) throw new Error(`unreachable: missing child \"${key}\"`);\n\t\t\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\t\t\treturn child.analyze(inputSchema, {\n\t\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn {\n\t\t\t\t\tvalid: true,\n\t\t\t\t\tdiagnostics: [],\n\t\t\t\t\toutputSchema: inferPrimitiveSchema(this.state.value),\n\t\t\t\t};\n\n\t\t\tcase \"template\":\n\t\t\t\treturn analyzeFromAst(this.state.ast, this.state.source, inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\thelpers: this.options.helpers,\n\t\t\t\t\tcoerceSchema: options?.coerceSchema,\n\t\t\t\t});\n\t\t}\n\t}\n\n\t// ─── Validation ──────────────────────────────────────────────────────\n\n\t/**\n\t * Validates the 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 inputSchema - JSON Schema describing the available variables\n\t * @param options - (optional) Analysis options (identifierSchemas, coerceSchema)\n\t */\n\tvalidate(\n\t\tinputSchema: JSONSchema7 = {},\n\t\toptions?: AnalyzeOptions,\n\t): ValidationResult {\n\t\tconst analysis = this.analyze(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// ─── Execution ───────────────────────────────────────────────────────\n\n\t/**\n\t * Executes this template with the provided data.\n\t *\n\t * The return type depends on the template structure:\n\t * - Single expression `{{expr}}` → raw value (number, boolean, object…)\n\t * - Mixed template or with blocks → `string`\n\t * - Primitive literal → the value as-is\n\t * - Object template → object with resolved values\n\t * - Array template → array with resolved values\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 data - The context data for rendering\n\t * @param options - Execution options (schema, identifierData, coerceSchema, etc.)\n\t * @returns The execution result\n\t */\n\texecute(data: TemplateData, options?: ExecuteOptions): unknown {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"array\": {\n\t\t\t\tconst { elements } = this.state;\n\t\t\t\tconst effective = exclude\n\t\t\t\t\t? elements.filter((el) => !isCompiledTemplateWithExpression(el))\n\t\t\t\t\t: elements;\n\t\t\t\tconst result: unknown[] = [];\n\t\t\t\tfor (const element of effective) {\n\t\t\t\t\tresult.push(element.execute(data, options));\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\tconst coerceSchema = options?.coerceSchema;\n\t\t\t\tconst keys = exclude\n\t\t\t\t\t? Object.keys(children).filter((key) => {\n\t\t\t\t\t\t\tconst child = children[key];\n\t\t\t\t\t\t\treturn !child || !isCompiledTemplateWithExpression(child);\n\t\t\t\t\t\t})\n\t\t\t\t\t: Object.keys(children);\n\t\t\t\tconst result: Record<string, unknown> = {};\n\t\t\t\tfor (const key of keys) {\n\t\t\t\t\tconst child = children[key];\n\t\t\t\t\tif (!child) continue;\n\t\t\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\t\t\tresult[key] = child.execute(data, {\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn this.state.value;\n\n\t\t\tcase \"template\": {\n\t\t\t\t// When excludeTemplateExpression is enabled at root level,\n\t\t\t\t// return null if the template contains Handlebars expressions\n\t\t\t\t// (there is no parent to remove it from).\n\t\t\t\tif (exclude && isCompiledTemplateWithExpression(this)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\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 = this.analyze(options.schema, {\n\t\t\t\t\t\tidentifierSchemas: options.identifierSchemas,\n\t\t\t\t\t\tcoerceSchema: options.coerceSchema,\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(\n\t\t\t\t\tthis.state.ast,\n\t\t\t\t\tthis.state.source,\n\t\t\t\t\tdata,\n\t\t\t\t\tthis.buildExecutorContext(options),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Combined Shortcuts ──────────────────────────────────────────────\n\n\t/**\n\t * Analyzes and executes the template in a single call.\n\t *\n\t * Returns both the analysis result and the executed value.\n\t * If analysis fails, `value` is `undefined`.\n\t *\n\t * @param inputSchema - JSON Schema describing the available variables\n\t * @param data - The context data for rendering\n\t * @param options - Additional options (identifierSchemas, identifierData, coerceSchema)\n\t * @returns `{ analysis, value }`\n\t */\n\tanalyzeAndExecute(\n\t\tinputSchema: JSONSchema7 = {},\n\t\tdata: TemplateData,\n\t\toptions?: {\n\t\t\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t\t\tidentifierData?: IdentifierData;\n\t\t\tcoerceSchema?: JSONSchema7;\n\t\t},\n\t): { analysis: AnalysisResult; value: unknown } {\n\t\tswitch (this.state.kind) {\n\t\t\tcase \"array\": {\n\t\t\t\tconst { elements } = this.state;\n\t\t\t\treturn aggregateArrayAnalysisAndExecution(elements.length, (index) => {\n\t\t\t\t\tconst element = elements[index];\n\t\t\t\t\tif (!element)\n\t\t\t\t\t\tthrow new Error(`unreachable: missing element at index ${index}`);\n\t\t\t\t\treturn element.analyzeAndExecute(inputSchema, data, options);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tcase \"object\": {\n\t\t\t\tconst { children } = this.state;\n\t\t\t\tconst coerceSchema = options?.coerceSchema;\n\t\t\t\treturn aggregateObjectAnalysisAndExecution(\n\t\t\t\t\tObject.keys(children),\n\t\t\t\t\t(key) => {\n\t\t\t\t\t\tconst child = children[key];\n\t\t\t\t\t\tif (!child) throw new Error(`unreachable: missing child \"${key}\"`);\n\t\t\t\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(\n\t\t\t\t\t\t\tcoerceSchema,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn child.analyzeAndExecute(inputSchema, data, {\n\t\t\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase \"literal\":\n\t\t\t\treturn {\n\t\t\t\t\tanalysis: {\n\t\t\t\t\t\tvalid: true,\n\t\t\t\t\t\tdiagnostics: [],\n\t\t\t\t\t\toutputSchema: inferPrimitiveSchema(this.state.value),\n\t\t\t\t\t},\n\t\t\t\t\tvalue: this.state.value,\n\t\t\t\t};\n\n\t\t\tcase \"template\": {\n\t\t\t\tconst analysis = this.analyze(inputSchema, {\n\t\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\t\tcoerceSchema: options?.coerceSchema,\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(\n\t\t\t\t\tthis.state.ast,\n\t\t\t\t\tthis.state.source,\n\t\t\t\t\tdata,\n\t\t\t\t\tthis.buildExecutorContext({\n\t\t\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\t\t\tcoerceSchema: options?.coerceSchema,\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\treturn { analysis, value };\n\t\t\t}\n\t\t}\n\t}\n\n\t// ─── Internals ───────────────────────────────────────────────────────\n\n\t/**\n\t * Builds the execution context for `executeFromAst`.\n\t *\n\t * Uses lazy Handlebars compilation: the template is only compiled\n\t * on the first call that needs it (not for single expressions).\n\t */\n\tprivate buildExecutorContext(options?: ExecuteOptions): ExecutorContext {\n\t\treturn {\n\t\t\tidentifierData: options?.identifierData,\n\t\t\tcompiledTemplate: this.getOrCompileHbs(),\n\t\t\thbs: this.options.hbs,\n\t\t\tcompilationCache: this.options.compilationCache,\n\t\t\tcoerceSchema: options?.coerceSchema,\n\t\t\thelpers: this.options.helpers,\n\t\t};\n\t}\n\n\t/**\n\t * Lazily compiles the Handlebars template and caches it.\n\t *\n\t * Compilation happens only once — subsequent calls return the\n\t * in-memory compiled template.\n\t *\n\t * Precondition: this method is only called from \"template\" mode.\n\t */\n\tprivate getOrCompileHbs(): HandlebarsTemplateDelegate {\n\t\tif (!this.hbsCompiled) {\n\t\t\t// In \"template\" mode, `this.template` returns the source string\n\t\t\tthis.hbsCompiled = this.options.hbs.compile(this.template, {\n\t\t\t\tnoEscape: true,\n\t\t\t\tstrict: false,\n\t\t\t});\n\t\t}\n\t\treturn this.hbsCompiled;\n\t}\n}\n\n// ─── Internal Helpers ────────────────────────────────────────────────────────\n\n/**\n * Determines whether a `CompiledTemplate` represents a string template\n * containing Handlebars expressions (`{{…}}`).\n *\n * Used by `excludeTemplateExpression` filtering to skip dynamic entries\n * in object and array modes.\n */\nfunction isCompiledTemplateWithExpression(ct: CompiledTemplate): boolean {\n\t// Only \"template\" kind can contain expressions. Literals, objects,\n\t// and arrays are never excluded at the entry level — objects and\n\t// arrays are recursively filtered by the analysis method itself.\n\treturn ct.template !== \"\" && shouldExcludeEntry(ct.template);\n}\n"],"names":["CompiledTemplate","ast","state","kind","template","source","fromTemplate","options","fromLiteral","value","fromObject","children","fromArray","elements","analyze","inputSchema","exclude","excludeTemplateExpression","kept","filter","el","isCompiledTemplateWithExpression","aggregateArrayAnalysis","length","index","element","Error","coerceSchema","keys","Object","key","child","aggregateObjectAnalysis","childCoerceSchema","resolveChildCoerceSchema","identifierSchemas","valid","diagnostics","outputSchema","inferPrimitiveSchema","analyzeFromAst","helpers","validate","analysis","execute","data","effective","result","push","schema","TemplateAnalysisError","executeFromAst","buildExecutorContext","analyzeAndExecute","aggregateArrayAnalysisAndExecution","aggregateObjectAnalysisAndExecution","identifierData","undefined","compiledTemplate","getOrCompileHbs","hbs","compilationCache","hbsCompiled","compile","noEscape","strict","ct","shouldExcludeEntry"],"mappings":"oGAqFaA,0DAAAA,8CAlFkB,2CAC8B,yCACvB,yCACe,wCAShB,mCAO9B,+LA+DA,MAAMA,iBAaZ,IAAIC,KAA8B,CACjC,OAAO,IAAI,CAACC,KAAK,CAACC,IAAI,GAAK,WAAa,IAAI,CAACD,KAAK,CAACD,GAAG,CAAG,IAC1D,CAGA,IAAIG,UAAmB,CACtB,OAAO,IAAI,CAACF,KAAK,CAACC,IAAI,GAAK,WAAa,IAAI,CAACD,KAAK,CAACG,MAAM,CAAG,EAC7D,CAgBA,OAAOC,aACNL,GAAoB,CACpBI,MAAc,CACdE,OAAgC,CACb,CACnB,OAAO,IAAIP,iBAAiB,CAAEG,KAAM,WAAYF,IAAKI,MAAO,EAAGE,QAChE,CAUA,OAAOC,YACNC,K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KAAK,CAAGA,KACb,CAAA,IAAI,CAACK,OAAO,CAAGA,OAChB,CAuYD,CAWA,SAASc,iCAAiC6C,EAAoB,EAI7D,OAAOA,GAAG9D,QAAQ,GAAK,IAAM+D,GAAAA,8BAAkB,EAACD,GAAG9D,QAAQ,CAC5D"}
@@ -1,5 +1,5 @@
1
1
  import type { JSONSchema7 } from "json-schema";
2
- import type { AnalysisResult, TemplateInput } from "./types.js";
2
+ import type { AnalysisResult, IdentifierData, TemplateInput } from "./types.js";
3
3
  /** Options controlling recursive dispatching behavior */
4
4
  export interface DispatchAnalyzeOptions {
5
5
  /** Schemas by template identifier */
@@ -47,7 +47,7 @@ export declare function dispatchExecute(template: TemplateInput, options: Dispat
47
47
  /** Options for combined analyze-and-execute dispatching */
48
48
  export interface DispatchAnalyzeAndExecuteOptions {
49
49
  identifierSchemas?: Record<number, JSONSchema7>;
50
- identifierData?: Record<number, Record<string, unknown>>;
50
+ identifierData?: IdentifierData;
51
51
  coerceSchema?: JSONSchema7;
52
52
  /** When true, exclude entries containing Handlebars expressions */
53
53
  excludeTemplateExpression?: boolean;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/dispatch.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { hasHandlebarsExpression } from \"./parser.ts\";\nimport { resolveSchemaPath } from \"./schema-resolver.ts\";\nimport type { AnalysisResult, TemplateInput } from \"./types.ts\";\nimport {\n\tinferPrimitiveSchema,\n\tisArrayInput,\n\tisLiteralInput,\n\tisObjectInput,\n} from \"./types.ts\";\nimport {\n\taggregateArrayAnalysis,\n\taggregateArrayAnalysisAndExecution,\n\taggregateObjectAnalysis,\n\taggregateObjectAnalysisAndExecution,\n} from \"./utils.ts\";\n\n// ─── Template Input Dispatching ──────────────────────────────────────────────\n// Factorized dispatching for recursive processing of `TemplateInput` values.\n//\n// Every method in the engine (`analyze`, `execute`, `analyzeAndExecute`,\n// `compile`) follows the same recursive pattern:\n//\n// 1. If the input is an **array** → process each element recursively\n// 2. If the input is an **object** → process each property recursively\n// 3. If the input is a **literal** (number, boolean, null) → passthrough\n// 4. If the input is a **string** → delegate to a template-specific handler\n//\n// This module extracts the common dispatching logic into generic functions\n// that accept a callback for the string (template) case. This eliminates\n// the duplication across `Typebars`, `CompiledTemplate`, and `analyzer.ts`.\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Options controlling recursive dispatching behavior */\nexport interface DispatchAnalyzeOptions {\n\t/** Schemas by template identifier */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Explicit coercion schema for static literal output type */\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n/** Options controlling recursive execution dispatching */\nexport interface DispatchExecuteOptions {\n\t/** Explicit coercion schema for output type coercion */\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n// ─── Analysis Dispatching ────────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for analysis, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to analyze\n * @param options - Dispatching options (coerceSchema, excludeTemplateExpression)\n * @param analyzeString - Callback for analyzing a string template.\n * Receives `(template, coerceSchema?)` and must return an `AnalysisResult`.\n * @param recurse - Callback for recursively analyzing a child `TemplateInput`.\n * Receives `(child, options?)` and must return an `AnalysisResult`.\n * This allows callers (like `Typebars`) to rebind `this` or inject\n * additional context on each recursive call.\n * @returns An `AnalysisResult`\n */\nexport function dispatchAnalyze(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeOptions | undefined,\n\tanalyzeString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => AnalysisResult,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\t\tconst childOptions = resolveArrayChildOptions(options);\n\t\tif (exclude) {\n\t\t\tconst kept = template.filter(\n\t\t\t\t(item) => !shouldExcludeEntry(item as TemplateInput),\n\t\t\t);\n\t\t\treturn aggregateArrayAnalysis(kept.length, (index) =>\n\t\t\t\trecurse(kept[index] as TemplateInput, childOptions),\n\t\t\t);\n\t\t}\n\t\treturn aggregateArrayAnalysis(template.length, (index) =>\n\t\t\trecurse(template[index] as TemplateInput, childOptions),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\treturn dispatchObjectAnalysis(template, options, recurse);\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) {\n\t\treturn {\n\t\t\tvalid: true,\n\t\t\tdiagnostics: [],\n\t\t\toutputSchema: inferPrimitiveSchema(template),\n\t\t};\n\t}\n\n\t// ── String template ──────────────────────────────────────────────────\n\treturn analyzeString(template, options?.coerceSchema);\n}\n\n/**\n * Dispatches object analysis with `coerceSchema` propagation and\n * `excludeTemplateExpression` filtering.\n *\n * Extracted as a separate function because the object case is the most\n * complex (key filtering + per-key coerceSchema resolution).\n */\nfunction dispatchObjectAnalysis(\n\ttemplate: Record<string, TemplateInput>,\n\toptions: DispatchAnalyzeOptions | undefined,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\tconst coerceSchema = options?.coerceSchema;\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\tconst keys = exclude\n\t\t? Object.keys(template).filter(\n\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t)\n\t\t: Object.keys(template);\n\n\treturn aggregateObjectAnalysis(keys, (key) => {\n\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t});\n\t});\n}\n\n// ─── Execution Dispatching ───────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for execution, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to execute\n * @param options - Dispatching options (coerceSchema)\n * @param executeString - Callback for executing a string template.\n * Receives `(template, coerceSchema?)` and must return the result.\n * @param recurse - Callback for recursively executing a child `TemplateInput`.\n * Receives `(child, options?)` and must return the result.\n * @returns The execution result\n */\nexport function dispatchExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchExecuteOptions | undefined,\n\texecuteString: (template: string, coerceSchema?: JSONSchema7) => unknown,\n\trecurse: (child: TemplateInput, options?: DispatchExecuteOptions) => unknown,\n): unknown {\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst childOptions = resolveArrayChildOptions(options);\n\t\tconst elements = exclude\n\t\t\t? template.filter((item) => !shouldExcludeEntry(item as TemplateInput))\n\t\t\t: template;\n\t\tconst result: unknown[] = [];\n\t\tfor (const element of elements) {\n\t\t\tresult.push(recurse(element as TemplateInput, childOptions));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\tconst result: Record<string, unknown> = {};\n\t\tconst keys = exclude\n\t\t\t? Object.keys(template).filter(\n\t\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t\t)\n\t\t\t: Object.keys(template);\n\t\tfor (const key of keys) {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\tresult[key] = recurse(template[key] as TemplateInput, {\n\t\t\t\t...options,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) return template;\n\n\t// ── String template ──────────────────────────────────────────────────\n\t// At root level, if the string contains expressions and exclude is on,\n\t// return null (there is no parent to remove it from).\n\tif (exclude && shouldExcludeEntry(template)) {\n\t\treturn null;\n\t}\n\n\treturn executeString(template, options?.coerceSchema);\n}\n\n// ─── Analyze-and-Execute Dispatching ─────────────────────────────────────────\n\n/** Options for combined analyze-and-execute dispatching */\nexport interface DispatchAnalyzeAndExecuteOptions {\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\tidentifierData?: Record<number, Record<string, unknown>>;\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n/**\n * Dispatches a `TemplateInput` for combined analysis and execution,\n * handling array/object/literal cases generically and delegating\n * the string case to a callback.\n *\n * @param template - The input to process\n * @param options - Options (identifierSchemas, identifierData, coerceSchema)\n * @param processString - Callback for analyzing and executing a string template.\n * Receives `(template, coerceSchema?)` and must return\n * `{ analysis, value }`.\n * @param recurse - Callback for recursively processing a child `TemplateInput`.\n * @returns `{ analysis, value }` where `value` is `undefined` if analysis fails\n */\nexport function dispatchAnalyzeAndExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeAndExecuteOptions | undefined,\n\tprocessString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => { analysis: AnalysisResult; value: unknown },\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeAndExecuteOptions,\n\t) => { analysis: AnalysisResult; value: unknown },\n): { analysis: AnalysisResult; value: unknown } {\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst childOptions = resolveArrayChildOptions(options);\n\t\tconst elements = exclude\n\t\t\t? template.filter((item) => !shouldExcludeEntry(item as TemplateInput))\n\t\t\t: template;\n\t\treturn aggregateArrayAnalysisAndExecution(elements.length, (index) =>\n\t\t\trecurse(elements[index] as TemplateInput, childOptions),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\tconst keys = exclude\n\t\t\t? Object.keys(template).filter(\n\t\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t\t)\n\t\t\t: Object.keys(template);\n\t\treturn aggregateObjectAnalysisAndExecution(keys, (key) => {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t\t});\n\t\t});\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) {\n\t\treturn {\n\t\t\tanalysis: {\n\t\t\t\tvalid: true,\n\t\t\t\tdiagnostics: [],\n\t\t\t\toutputSchema: inferPrimitiveSchema(template),\n\t\t\t},\n\t\t\tvalue: template,\n\t\t};\n\t}\n\n\t// ── String template ──────────────────────────────────────────────────\n\t// At root level, if the string contains expressions and exclude is on,\n\t// return null with a valid analysis (no parent to remove from).\n\tif (exclude && shouldExcludeEntry(template)) {\n\t\treturn {\n\t\t\tanalysis: {\n\t\t\t\tvalid: true,\n\t\t\t\tdiagnostics: [],\n\t\t\t\toutputSchema: { type: \"null\" },\n\t\t\t},\n\t\t\tvalue: null,\n\t\t};\n\t}\n\n\treturn processString(template, options?.coerceSchema);\n}\n\n// ─── Internal Utilities ──────────────────────────────────────────────────────\n\n/**\n * Resolves the child options for array element recursion.\n *\n * When a `coerceSchema` with `items` is provided, the child options\n * will use `coerceSchema.items` as the element-level coercion schema.\n * All other options are passed through unchanged.\n *\n * @param options - The parent dispatching options (may be `undefined`)\n * @returns New options with `coerceSchema` resolved to the items schema, or\n * the original options if no items schema is available.\n */\nfunction resolveArrayChildOptions<\n\tT extends { coerceSchema?: JSONSchema7 } | undefined,\n>(options: T): T {\n\tif (!options?.coerceSchema) return options;\n\n\tconst itemsSchema = resolveItemsCoerceSchema(options.coerceSchema);\n\tif (itemsSchema === options.coerceSchema) return options;\n\n\treturn { ...options, coerceSchema: itemsSchema };\n}\n\n/**\n * Extracts the `items` schema from an array-typed `coerceSchema`.\n *\n * If the schema declares `items` as a single schema (not a tuple),\n * returns that schema. Otherwise returns `undefined`.\n *\n * @param coerceSchema - The parent coercion schema\n * @returns The items coercion schema, or `undefined`\n */\nfunction resolveItemsCoerceSchema(\n\tcoerceSchema: JSONSchema7,\n): JSONSchema7 | undefined {\n\tif (typeof coerceSchema === \"boolean\") return undefined;\n\n\tconst items = coerceSchema.items;\n\tif (items != null && typeof items === \"object\" && !Array.isArray(items)) {\n\t\treturn items as JSONSchema7;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Resolves the child `coerceSchema` for a given object key.\n *\n * When a `coerceSchema` is provided, navigates into its `properties`\n * to find the schema for the given key. This allows deeply nested\n * objects to propagate coercion at every level.\n *\n * @param coerceSchema - The parent coercion schema (may be `undefined`)\n * @param key - The object property key\n * @returns The child coercion schema, or `undefined`\n */\nexport function resolveChildCoerceSchema(\n\tcoerceSchema: JSONSchema7 | undefined,\n\tkey: string,\n): JSONSchema7 | undefined {\n\treturn coerceSchema ? resolveSchemaPath(coerceSchema, [key]) : undefined;\n}\n\n/**\n * Determines whether a `TemplateInput` value should be excluded when\n * `excludeTemplateExpression` is enabled.\n *\n * A value is excluded if it is a string containing at least one Handlebars\n * expression (`{{…}}`). Literals (number, boolean, null), plain strings\n * without expressions, objects, and arrays are never excluded at the\n * entry level — objects and arrays are recursively filtered by the\n * dispatching functions themselves.\n *\n * @param input - The template input to check\n * @returns `true` if the input should be excluded\n */\nexport function shouldExcludeEntry(input: TemplateInput): boolean {\n\treturn typeof input === \"string\" && hasHandlebarsExpression(input);\n}\n"],"names":["dispatchAnalyze","dispatchAnalyzeAndExecute","dispatchExecute","resolveChildCoerceSchema","shouldExcludeEntry","template","options","analyzeString","recurse","isArrayInput","exclude","excludeTemplateExpression","childOptions","resolveArrayChildOptions","kept","filter","item","aggregateArrayAnalysis","length","index","isObjectInput","dispatchObjectAnalysis","isLiteralInput","valid","diagnostics","outputSchema","inferPrimitiveSchema","coerceSchema","keys","Object","key","aggregateObjectAnalysis","childCoerceSchema","identifierSchemas","executeString","elements","result","element","push","processString","aggregateArrayAnalysisAndExecution","aggregateObjectAnalysisAndExecution","identifierData","analysis","value","type","itemsSchema","resolveItemsCoerceSchema","undefined","items","Array","isArray","resolveSchemaPath","input","hasHandlebarsExpression"],"mappings":"mPAoEgBA,yBAAAA,qBA4KAC,mCAAAA,+BA7EAC,yBAAAA,qBA+MAC,kCAAAA,8BAoBAC,4BAAAA,8CArYwB,+CACN,+CAO3B,qCAMA,cAqDA,SAASJ,gBACfK,QAAuB,CACvBC,OAA2C,CAC3CC,aAGmB,CACnBC,OAGmB,EAGnB,GAAIC,GAAAA,qBAAY,EAACJ,UAAW,CAC3B,MAAMK,QAAUJ,SAASK,4BAA8B,KACvD,MAAMC,aAAeC,yBAAyBP,SAC9C,GAAII,QAAS,CACZ,MAAMI,KAAOT,SAASU,MAAM,CAC3B,AAACC,MAAS,CAACZ,mBAAmBY,OAE/B,MAAOC,GAAAA,+BAAsB,EAACH,KAAKI,MAAM,CAAE,AAACC,OAC3CX,QAAQM,IAAI,CAACK,MAAM,CAAmBP,cAExC,CACA,MAAOK,GAAAA,+BAAsB,EAACZ,SAASa,MAAM,CAAE,AAACC,OAC/CX,QAAQH,QAAQ,CAACc,MAAM,CAAmBP,cAE5C,CAGA,GAAIQ,GAAAA,sBAAa,EAACf,UAAW,CAC5B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CAAmB,CAC9CG,kBAAmB3B,SAAS2B,kBAC5BS,eAAgBpC,SAASoC,eACzBf,aAAcK,kBACdrB,0BAA2BL,SAASK,yBACrC,EACD,EACD,CAGA,GAAIW,GAAAA,uBAAc,EAACjB,UAAW,CAC7B,MAAO,CACNsC,SAAU,CACTpB,MAAO,KACPC,YAAa,EAAE,CACfC,aAAcC,GAAAA,6BAAoB,EAACrB,SACpC,EACAuC,MAAOvC,QACR,CACD,CAKA,GAAIK,SAAWN,mBAAmBC,UAAW,CAC5C,MAAO,CACNsC,SAAU,CACTpB,MAAO,KACPC,YAAa,EAAE,CACfC,aAAc,CAAEoB,KAAM,MAAO,CAC9B,EACAD,MAAO,IACR,CACD,CAEA,OAAOL,cAAclC,SAAUC,SAASqB,aACzC,CAeA,SAASd,yBAEPP,OAAU,EACX,GAAI,CAACA,SAASqB,aAAc,OAAOrB,QAEnC,MAAMwC,YAAcC,yBAAyBzC,QAAQqB,YAAY,EACjE,GAAImB,cAAgBxC,QAAQqB,YAAY,CAAE,OAAOrB,QAEjD,MAAO,CAAE,GAAGA,OAAO,CAAEqB,aAAcmB,WAAY,CAChD,CAWA,SAASC,yBACRpB,YAAyB,EAEzB,GAAI,OAAOA,eAAiB,UAAW,OAAOqB,UAE9C,MAAMC,MAAQtB,aAAasB,KAAK,CAChC,GAAIA,OAAS,MAAQ,OAAOA,QAAU,UAAY,CAACC,MAAMC,OAAO,CAACF,OAAQ,CACxE,OAAOA,KACR,CAEA,OAAOD,SACR,CAaO,SAAS7C,yBACfwB,YAAqC,CACrCG,GAAW,EAEX,OAAOH,aAAeyB,GAAAA,mCAAiB,EAACzB,aAAc,CAACG,IAAI,EAAIkB,SAChE,CAeO,SAAS5C,mBAAmBiD,KAAoB,EACtD,OAAO,OAAOA,QAAU,UAAYC,GAAAA,iCAAuB,EAACD,MAC7D"}
1
+ {"version":3,"sources":["../../src/dispatch.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport { hasHandlebarsExpression } from \"./parser.ts\";\nimport { resolveSchemaPath } from \"./schema-resolver.ts\";\nimport type { AnalysisResult, IdentifierData, TemplateInput } from \"./types.ts\";\nimport {\n\tinferPrimitiveSchema,\n\tisArrayInput,\n\tisLiteralInput,\n\tisObjectInput,\n} from \"./types.ts\";\nimport {\n\taggregateArrayAnalysis,\n\taggregateArrayAnalysisAndExecution,\n\taggregateObjectAnalysis,\n\taggregateObjectAnalysisAndExecution,\n} from \"./utils.ts\";\n\n// ─── Template Input Dispatching ──────────────────────────────────────────────\n// Factorized dispatching for recursive processing of `TemplateInput` values.\n//\n// Every method in the engine (`analyze`, `execute`, `analyzeAndExecute`,\n// `compile`) follows the same recursive pattern:\n//\n// 1. If the input is an **array** → process each element recursively\n// 2. If the input is an **object** → process each property recursively\n// 3. If the input is a **literal** (number, boolean, null) → passthrough\n// 4. If the input is a **string** → delegate to a template-specific handler\n//\n// This module extracts the common dispatching logic into generic functions\n// that accept a callback for the string (template) case. This eliminates\n// the duplication across `Typebars`, `CompiledTemplate`, and `analyzer.ts`.\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Options controlling recursive dispatching behavior */\nexport interface DispatchAnalyzeOptions {\n\t/** Schemas by template identifier */\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\t/** Explicit coercion schema for static literal output type */\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n/** Options controlling recursive execution dispatching */\nexport interface DispatchExecuteOptions {\n\t/** Explicit coercion schema for output type coercion */\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n// ─── Analysis Dispatching ────────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for analysis, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to analyze\n * @param options - Dispatching options (coerceSchema, excludeTemplateExpression)\n * @param analyzeString - Callback for analyzing a string template.\n * Receives `(template, coerceSchema?)` and must return an `AnalysisResult`.\n * @param recurse - Callback for recursively analyzing a child `TemplateInput`.\n * Receives `(child, options?)` and must return an `AnalysisResult`.\n * This allows callers (like `Typebars`) to rebind `this` or inject\n * additional context on each recursive call.\n * @returns An `AnalysisResult`\n */\nexport function dispatchAnalyze(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeOptions | undefined,\n\tanalyzeString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => AnalysisResult,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst exclude = options?.excludeTemplateExpression === true;\n\t\tconst childOptions = resolveArrayChildOptions(options);\n\t\tif (exclude) {\n\t\t\tconst kept = template.filter(\n\t\t\t\t(item) => !shouldExcludeEntry(item as TemplateInput),\n\t\t\t);\n\t\t\treturn aggregateArrayAnalysis(kept.length, (index) =>\n\t\t\t\trecurse(kept[index] as TemplateInput, childOptions),\n\t\t\t);\n\t\t}\n\t\treturn aggregateArrayAnalysis(template.length, (index) =>\n\t\t\trecurse(template[index] as TemplateInput, childOptions),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\treturn dispatchObjectAnalysis(template, options, recurse);\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) {\n\t\treturn {\n\t\t\tvalid: true,\n\t\t\tdiagnostics: [],\n\t\t\toutputSchema: inferPrimitiveSchema(template),\n\t\t};\n\t}\n\n\t// ── String template ──────────────────────────────────────────────────\n\treturn analyzeString(template, options?.coerceSchema);\n}\n\n/**\n * Dispatches object analysis with `coerceSchema` propagation and\n * `excludeTemplateExpression` filtering.\n *\n * Extracted as a separate function because the object case is the most\n * complex (key filtering + per-key coerceSchema resolution).\n */\nfunction dispatchObjectAnalysis(\n\ttemplate: Record<string, TemplateInput>,\n\toptions: DispatchAnalyzeOptions | undefined,\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeOptions,\n\t) => AnalysisResult,\n): AnalysisResult {\n\tconst coerceSchema = options?.coerceSchema;\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\tconst keys = exclude\n\t\t? Object.keys(template).filter(\n\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t)\n\t\t: Object.keys(template);\n\n\treturn aggregateObjectAnalysis(keys, (key) => {\n\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t});\n\t});\n}\n\n// ─── Execution Dispatching ───────────────────────────────────────────────────\n\n/**\n * Dispatches a `TemplateInput` for execution, handling the array/object/literal\n * cases generically and delegating the string (template) case to a callback.\n *\n * @param template - The input to execute\n * @param options - Dispatching options (coerceSchema)\n * @param executeString - Callback for executing a string template.\n * Receives `(template, coerceSchema?)` and must return the result.\n * @param recurse - Callback for recursively executing a child `TemplateInput`.\n * Receives `(child, options?)` and must return the result.\n * @returns The execution result\n */\nexport function dispatchExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchExecuteOptions | undefined,\n\texecuteString: (template: string, coerceSchema?: JSONSchema7) => unknown,\n\trecurse: (child: TemplateInput, options?: DispatchExecuteOptions) => unknown,\n): unknown {\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst childOptions = resolveArrayChildOptions(options);\n\t\tconst elements = exclude\n\t\t\t? template.filter((item) => !shouldExcludeEntry(item as TemplateInput))\n\t\t\t: template;\n\t\tconst result: unknown[] = [];\n\t\tfor (const element of elements) {\n\t\t\tresult.push(recurse(element as TemplateInput, childOptions));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\tconst result: Record<string, unknown> = {};\n\t\tconst keys = exclude\n\t\t\t? Object.keys(template).filter(\n\t\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t\t)\n\t\t\t: Object.keys(template);\n\t\tfor (const key of keys) {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\tresult[key] = recurse(template[key] as TemplateInput, {\n\t\t\t\t...options,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) return template;\n\n\t// ── String template ──────────────────────────────────────────────────\n\t// At root level, if the string contains expressions and exclude is on,\n\t// return null (there is no parent to remove it from).\n\tif (exclude && shouldExcludeEntry(template)) {\n\t\treturn null;\n\t}\n\n\treturn executeString(template, options?.coerceSchema);\n}\n\n// ─── Analyze-and-Execute Dispatching ─────────────────────────────────────────\n\n/** Options for combined analyze-and-execute dispatching */\nexport interface DispatchAnalyzeAndExecuteOptions {\n\tidentifierSchemas?: Record<number, JSONSchema7>;\n\tidentifierData?: IdentifierData;\n\tcoerceSchema?: JSONSchema7;\n\t/** When true, exclude entries containing Handlebars expressions */\n\texcludeTemplateExpression?: boolean;\n}\n\n/**\n * Dispatches a `TemplateInput` for combined analysis and execution,\n * handling array/object/literal cases generically and delegating\n * the string case to a callback.\n *\n * @param template - The input to process\n * @param options - Options (identifierSchemas, identifierData, coerceSchema)\n * @param processString - Callback for analyzing and executing a string template.\n * Receives `(template, coerceSchema?)` and must return\n * `{ analysis, value }`.\n * @param recurse - Callback for recursively processing a child `TemplateInput`.\n * @returns `{ analysis, value }` where `value` is `undefined` if analysis fails\n */\nexport function dispatchAnalyzeAndExecute(\n\ttemplate: TemplateInput,\n\toptions: DispatchAnalyzeAndExecuteOptions | undefined,\n\tprocessString: (\n\t\ttemplate: string,\n\t\tcoerceSchema?: JSONSchema7,\n\t) => { analysis: AnalysisResult; value: unknown },\n\trecurse: (\n\t\tchild: TemplateInput,\n\t\toptions?: DispatchAnalyzeAndExecuteOptions,\n\t) => { analysis: AnalysisResult; value: unknown },\n): { analysis: AnalysisResult; value: unknown } {\n\tconst exclude = options?.excludeTemplateExpression === true;\n\n\t// ── Array ─────────────────────────────────────────────────────────────\n\tif (isArrayInput(template)) {\n\t\tconst childOptions = resolveArrayChildOptions(options);\n\t\tconst elements = exclude\n\t\t\t? template.filter((item) => !shouldExcludeEntry(item as TemplateInput))\n\t\t\t: template;\n\t\treturn aggregateArrayAnalysisAndExecution(elements.length, (index) =>\n\t\t\trecurse(elements[index] as TemplateInput, childOptions),\n\t\t);\n\t}\n\n\t// ── Object ────────────────────────────────────────────────────────────\n\tif (isObjectInput(template)) {\n\t\tconst coerceSchema = options?.coerceSchema;\n\t\tconst keys = exclude\n\t\t\t? Object.keys(template).filter(\n\t\t\t\t\t(key) => !shouldExcludeEntry(template[key] as TemplateInput),\n\t\t\t\t)\n\t\t\t: Object.keys(template);\n\t\treturn aggregateObjectAnalysisAndExecution(keys, (key) => {\n\t\t\tconst childCoerceSchema = resolveChildCoerceSchema(coerceSchema, key);\n\t\t\treturn recurse(template[key] as TemplateInput, {\n\t\t\t\tidentifierSchemas: options?.identifierSchemas,\n\t\t\t\tidentifierData: options?.identifierData,\n\t\t\t\tcoerceSchema: childCoerceSchema,\n\t\t\t\texcludeTemplateExpression: options?.excludeTemplateExpression,\n\t\t\t});\n\t\t});\n\t}\n\n\t// ── Literal (number, boolean, null) ───────────────────────────────────\n\tif (isLiteralInput(template)) {\n\t\treturn {\n\t\t\tanalysis: {\n\t\t\t\tvalid: true,\n\t\t\t\tdiagnostics: [],\n\t\t\t\toutputSchema: inferPrimitiveSchema(template),\n\t\t\t},\n\t\t\tvalue: template,\n\t\t};\n\t}\n\n\t// ── String template ──────────────────────────────────────────────────\n\t// At root level, if the string contains expressions and exclude is on,\n\t// return null with a valid analysis (no parent to remove from).\n\tif (exclude && shouldExcludeEntry(template)) {\n\t\treturn {\n\t\t\tanalysis: {\n\t\t\t\tvalid: true,\n\t\t\t\tdiagnostics: [],\n\t\t\t\toutputSchema: { type: \"null\" },\n\t\t\t},\n\t\t\tvalue: null,\n\t\t};\n\t}\n\n\treturn processString(template, options?.coerceSchema);\n}\n\n// ─── Internal Utilities ──────────────────────────────────────────────────────\n\n/**\n * Resolves the child options for array element recursion.\n *\n * When a `coerceSchema` with `items` is provided, the child options\n * will use `coerceSchema.items` as the element-level coercion schema.\n * All other options are passed through unchanged.\n *\n * @param options - The parent dispatching options (may be `undefined`)\n * @returns New options with `coerceSchema` resolved to the items schema, or\n * the original options if no items schema is available.\n */\nfunction resolveArrayChildOptions<\n\tT extends { coerceSchema?: JSONSchema7 } | undefined,\n>(options: T): T {\n\tif (!options?.coerceSchema) return options;\n\n\tconst itemsSchema = resolveItemsCoerceSchema(options.coerceSchema);\n\tif (itemsSchema === options.coerceSchema) return options;\n\n\treturn { ...options, coerceSchema: itemsSchema };\n}\n\n/**\n * Extracts the `items` schema from an array-typed `coerceSchema`.\n *\n * If the schema declares `items` as a single schema (not a tuple),\n * returns that schema. Otherwise returns `undefined`.\n *\n * @param coerceSchema - The parent coercion schema\n * @returns The items coercion schema, or `undefined`\n */\nfunction resolveItemsCoerceSchema(\n\tcoerceSchema: JSONSchema7,\n): JSONSchema7 | undefined {\n\tif (typeof coerceSchema === \"boolean\") return undefined;\n\n\tconst items = coerceSchema.items;\n\tif (items != null && typeof items === \"object\" && !Array.isArray(items)) {\n\t\treturn items as JSONSchema7;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Resolves the child `coerceSchema` for a given object key.\n *\n * When a `coerceSchema` is provided, navigates into its `properties`\n * to find the schema for the given key. This allows deeply nested\n * objects to propagate coercion at every level.\n *\n * @param coerceSchema - The parent coercion schema (may be `undefined`)\n * @param key - The object property key\n * @returns The child coercion schema, or `undefined`\n */\nexport function resolveChildCoerceSchema(\n\tcoerceSchema: JSONSchema7 | undefined,\n\tkey: string,\n): JSONSchema7 | undefined {\n\treturn coerceSchema ? resolveSchemaPath(coerceSchema, [key]) : undefined;\n}\n\n/**\n * Determines whether a `TemplateInput` value should be excluded when\n * `excludeTemplateExpression` is enabled.\n *\n * A value is excluded if it is a string containing at least one Handlebars\n * expression (`{{…}}`). Literals (number, boolean, null), plain strings\n * without expressions, objects, and arrays are never excluded at the\n * entry level — objects and arrays are recursively filtered by the\n * dispatching functions themselves.\n *\n * @param input - The template input to check\n * @returns `true` if the input should be excluded\n */\nexport function shouldExcludeEntry(input: TemplateInput): boolean {\n\treturn typeof input === \"string\" && hasHandlebarsExpression(input);\n}\n"],"names":["dispatchAnalyze","dispatchAnalyzeAndExecute","dispatchExecute","resolveChildCoerceSchema","shouldExcludeEntry","template","options","analyzeString","recurse","isArrayInput","exclude","excludeTemplateExpression","childOptions","resolveArrayChildOptions","kept","filter","item","aggregateArrayAnalysis","length","index","isObjectInput","dispatchObjectAnalysis","isLiteralInput","valid","diagnostics","outputSchema","inferPrimitiveSchema","coerceSchema","keys","Object","key","aggregateObjectAnalysis","childCoerceSchema","identifierSchemas","executeString","elements","result","element","push","processString","aggregateArrayAnalysisAndExecution","aggregateObjectAnalysisAndExecution","identifierData","analysis","value","type","itemsSchema","resolveItemsCoerceSchema","undefined","items","Array","isArray","resolveSchemaPath","input","hasHandlebarsExpression"],"mappings":"mPAoEgBA,yBAAAA,qBA4KAC,mCAAAA,+BA7EAC,yBAAAA,qBA+MAC,kCAAAA,8BAoBAC,4BAAAA,8CArYwB,+CACN,+CAO3B,qCAMA,cAqDA,SAASJ,gBACfK,QAAuB,CACvBC,OAA2C,CAC3CC,aAGmB,CACnBC,OAGmB,EAGnB,GAAIC,GAAAA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MAAQtB,aAAasB,KAAK,CAChC,GAAIA,OAAS,MAAQ,OAAOA,QAAU,UAAY,CAACC,MAAMC,OAAO,CAACF,OAAQ,CACxE,OAAOA,KACR,CAEA,OAAOD,SACR,CAaO,SAAS7C,yBACfwB,YAAqC,CACrCG,GAAW,EAEX,OAAOH,aAAeyB,GAAAA,mCAAiB,EAACzB,aAAc,CAACG,IAAI,EAAIkB,SAChE,CAeO,SAAS5C,mBAAmBiD,KAAoB,EACtD,OAAO,OAAOA,QAAU,UAAYC,GAAAA,iCAAuB,EAACD,MAC7D"}
@@ -1,11 +1,17 @@
1
1
  import Handlebars from "handlebars";
2
2
  import type { JSONSchema7 } from "json-schema";
3
- import type { HelperDefinition, TemplateInput } from "./types.js";
3
+ import type { HelperDefinition, IdentifierData, TemplateInput } from "./types.js";
4
4
  import { LRUCache } from "./utils.js";
5
5
  /** Optional context for execution (used by Typebars/CompiledTemplate) */
6
6
  export interface ExecutorContext {
7
- /** Data by identifier `{ [id]: { key: value } }` */
8
- identifierData?: Record<number, Record<string, unknown>>;
7
+ /**
8
+ * Data by identifier `{ [id]: { key: value } }`.
9
+ *
10
+ * Each identifier can map to a single object (standard) or an array
11
+ * of objects (aggregated multi-version data). When the value is an
12
+ * array, `{{key:N}}` extracts the property from each element.
13
+ */
14
+ identifierData?: IdentifierData;
9
15
  /** Pre-compiled Handlebars template (for CompiledTemplate) */
10
16
  compiledTemplate?: HandlebarsTemplateDelegate;
11
17
  /** Isolated Handlebars environment (for custom helpers) */
@@ -33,7 +39,7 @@ export interface ExecutorContext {
33
39
  * @param data - The main context data
34
40
  * @param identifierData - (optional) Data by identifier `{ [id]: { key: value } }`
35
41
  */
36
- export declare function execute(template: TemplateInput, data: unknown, identifierData?: Record<number, Record<string, unknown>>): unknown;
42
+ export declare function execute(template: TemplateInput, data: unknown, identifierData?: IdentifierData): unknown;
37
43
  /**
38
44
  * Executes a template from an already-parsed AST.
39
45
  *
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get clearCompilationCache(){return clearCompilationCache},get execute(){return execute},get executeFromAst(){return executeFromAst},get resolveDataPath(){return resolveDataPath}});const _handlebars=/*#__PURE__*/_interop_require_default(require("handlebars"));const _dispatchts=require("./dispatch.js");const _errorsts=require("./errors.js");const _maphelpersts=require("./helpers/map-helpers.js");const _parserts=require("./parser.js");const _utilsts=require("./utils.js");function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}const globalCompilationCache=new _utilsts.LRUCache(128);function execute(template,data,identifierData){return(0,_dispatchts.dispatchExecute)(template,undefined,tpl=>{const ast=(0,_parserts.parse)(tpl);return executeFromAst(ast,tpl,data,{identifierData})},child=>execute(child,data,identifierData))}function executeFromAst(ast,template,data,ctx){const identifierData=ctx?.identifierData;if((0,_parserts.isSingleExpression)(ast)){const stmt=ast.body[0];if(stmt.params.length===0&&!stmt.hash){return resolveExpression(stmt.path,data,identifierData,ctx?.helpers)}}const singleExpr=(0,_parserts.getEffectivelySingleExpression)(ast);if(singleExpr&&singleExpr.params.length===0&&!singleExpr.hash){return resolveExpression(singleExpr.path,data,identifierData,ctx?.helpers)}if(singleExpr&&(singleExpr.params.length>0||singleExpr.hash)){const directResult=tryDirectHelperExecution(singleExpr,data,ctx);if(directResult!==undefined){return directResult.value}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return coerceValue(raw,ctx?.coerceSchema)}if((0,_parserts.canUseFastPath)(ast)&&ast.body.length>1){return executeFastPath(ast,data,identifierData)}const singleBlock=(0,_parserts.getEffectivelySingleBlock)(ast);if(singleBlock){const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return coerceValue(raw,ctx?.coerceSchema)}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);const effective=(0,_parserts.getEffectiveBody)(ast);const allContent=effective.every(s=>s.type==="ContentStatement");if(allContent){return coerceValue(raw,ctx?.coerceSchema)}return raw}function coerceValue(raw,coerceSchema){if(coerceSchema){const targetType=coerceSchema.type;if(typeof targetType==="string"){if(targetType==="string")return raw;if(targetType==="number"||targetType==="integer"){const trimmed=raw.trim();if(trimmed==="")return undefined;const num=Number(trimmed);if(Number.isNaN(num))return undefined;if(targetType==="integer"&&!Number.isInteger(num))return undefined;return num}if(targetType==="boolean"){const lower=raw.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false;return undefined}if(targetType==="null")return null}}return(0,_parserts.coerceLiteral)(raw)}function executeFastPath(ast,data,identifierData){let result="";for(const stmt of ast.body){if(stmt.type==="ContentStatement"){result+=stmt.value}else if(stmt.type==="MustacheStatement"){const value=resolveExpression(stmt.path,data,identifierData);if(value!=null){result+=String(value)}}}return result}function resolveExpression(expr,data,identifierData,helpers){if((0,_parserts.isThisExpression)(expr)){return data}if(expr.type==="StringLiteral")return expr.value;if(expr.type==="NumberLiteral")return expr.value;if(expr.type==="BooleanLiteral")return expr.value;if(expr.type==="NullLiteral")return null;if(expr.type==="UndefinedLiteral")return undefined;if(expr.type==="SubExpression"){const subExpr=expr;if(subExpr.path.type==="PathExpression"){const helperName=subExpr.path.original;const helper=helpers?.get(helperName);if(helper){const isMap=helperName===_maphelpersts.MapHelpers.MAP_HELPER_NAME;const resolvedArgs=[];for(let i=0;i<subExpr.params.length;i++){const param=subExpr.params[i];if(isMap&&i===1&&param.type==="StringLiteral"){resolvedArgs.push(param.value)}else{resolvedArgs.push(resolveExpression(param,data,identifierData,helpers))}}return helper.fn(...resolvedArgs)}}return undefined}const segments=(0,_parserts.extractPathSegments)(expr);if(segments.length===0){throw new _errorsts.TemplateRuntimeError(`Cannot resolve expression of type "${expr.type}"`)}const{cleanSegments,identifier}=(0,_parserts.extractExpressionIdentifier)(segments);if((0,_parserts.isRootPathTraversal)(cleanSegments)){return undefined}if((0,_parserts.isRootSegments)(cleanSegments)){if(identifier!==null&&identifierData){const source=identifierData[identifier];return source??undefined}if(identifier!==null){return undefined}return data}if(identifier!==null&&identifierData){const source=identifierData[identifier];if(source){return resolveDataPath(source,cleanSegments)}return undefined}if(identifier!==null&&!identifierData){return undefined}return resolveDataPath(data,cleanSegments)}function resolveDataPath(data,segments){let current=data;for(const segment of segments){if(current===null||current===undefined){return undefined}if(typeof current!=="object"){return undefined}current=current[segment]}return current}function mergeDataWithIdentifiers(data,identifierData){const base=data!==null&&typeof data==="object"&&!Array.isArray(data)?data:{};const merged={...base,[_parserts.ROOT_TOKEN]:data};if(!identifierData)return merged;for(const[id,idData]of Object.entries(identifierData)){merged[`${_parserts.ROOT_TOKEN}:${id}`]=idData;for(const[key,value]of Object.entries(idData)){merged[`${key}:${id}`]=value}}return merged}function renderWithHandlebars(template,data,ctx){try{if(ctx?.compiledTemplate){return ctx.compiledTemplate(data)}const cache=ctx?.compilationCache??globalCompilationCache;const hbs=ctx?.hbs??_handlebars.default;let compiled=cache.get(template);if(!compiled){compiled=hbs.compile(template,{noEscape:true,strict:false});cache.set(template,compiled)}return compiled(data)}catch(error){const message=error instanceof Error?error.message:String(error);throw new _errorsts.TemplateRuntimeError(message)}}function clearCompilationCache(){globalCompilationCache.clear()}const DIRECT_EXECUTION_HELPERS=new Set([_maphelpersts.MapHelpers.MAP_HELPER_NAME]);function tryDirectHelperExecution(stmt,data,ctx){if(stmt.path.type!=="PathExpression")return undefined;const helperName=stmt.path.original;if(!DIRECT_EXECUTION_HELPERS.has(helperName))return undefined;const helper=ctx?.helpers?.get(helperName);if(!helper)return undefined;const isMap=helperName===_maphelpersts.MapHelpers.MAP_HELPER_NAME;const resolvedArgs=[];for(let i=0;i<stmt.params.length;i++){const param=stmt.params[i];if(isMap&&i===1){if(param.type==="StringLiteral"){resolvedArgs.push(param.value)}else{resolvedArgs.push(resolveExpression(param,data,ctx?.identifierData,ctx?.helpers))}}else{resolvedArgs.push(resolveExpression(param,data,ctx?.identifierData,ctx?.helpers))}}const value=helper.fn(...resolvedArgs);return{value}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:true,get:Object.getOwnPropertyDescriptor(all,name).get})}_export(exports,{get clearCompilationCache(){return clearCompilationCache},get execute(){return execute},get executeFromAst(){return executeFromAst},get resolveDataPath(){return resolveDataPath}});const _handlebars=/*#__PURE__*/_interop_require_default(require("handlebars"));const _dispatchts=require("./dispatch.js");const _errorsts=require("./errors.js");const _maphelpersts=require("./helpers/map-helpers.js");const _parserts=require("./parser.js");const _utilsts=require("./utils.js");function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}const globalCompilationCache=new _utilsts.LRUCache(128);function execute(template,data,identifierData){return(0,_dispatchts.dispatchExecute)(template,undefined,tpl=>{const ast=(0,_parserts.parse)(tpl);return executeFromAst(ast,tpl,data,{identifierData})},child=>execute(child,data,identifierData))}function executeFromAst(ast,template,data,ctx){const identifierData=ctx?.identifierData;if((0,_parserts.isSingleExpression)(ast)){const stmt=ast.body[0];if(stmt.params.length===0&&!stmt.hash){return resolveExpression(stmt.path,data,identifierData,ctx?.helpers)}}const singleExpr=(0,_parserts.getEffectivelySingleExpression)(ast);if(singleExpr&&singleExpr.params.length===0&&!singleExpr.hash){return resolveExpression(singleExpr.path,data,identifierData,ctx?.helpers)}if(singleExpr&&(singleExpr.params.length>0||singleExpr.hash)){const directResult=tryDirectHelperExecution(singleExpr,data,ctx);if(directResult!==undefined){return directResult.value}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return coerceValue(raw,ctx?.coerceSchema)}if((0,_parserts.canUseFastPath)(ast)&&ast.body.length>1){return executeFastPath(ast,data,identifierData)}const singleBlock=(0,_parserts.getEffectivelySingleBlock)(ast);if(singleBlock){const directResult=tryDirectBlockExecution(singleBlock,data,ctx);if(directResult!==undefined){return directResult.value}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);return coerceValue(raw,ctx?.coerceSchema)}const merged=mergeDataWithIdentifiers(data,identifierData);const raw=renderWithHandlebars(template,merged,ctx);const effective=(0,_parserts.getEffectiveBody)(ast);const allContent=effective.every(s=>s.type==="ContentStatement");if(allContent){return coerceValue(raw,ctx?.coerceSchema)}return raw}function coerceValue(raw,coerceSchema){if(coerceSchema){const targetType=coerceSchema.type;if(typeof targetType==="string"){if(targetType==="string")return raw;if(targetType==="number"||targetType==="integer"){const trimmed=raw.trim();if(trimmed==="")return undefined;const num=Number(trimmed);if(Number.isNaN(num))return undefined;if(targetType==="integer"&&!Number.isInteger(num))return undefined;return num}if(targetType==="boolean"){const lower=raw.trim().toLowerCase();if(lower==="true")return true;if(lower==="false")return false;return undefined}if(targetType==="null")return null}}return(0,_parserts.coerceLiteral)(raw)}function executeFastPath(ast,data,identifierData){let result="";for(const stmt of ast.body){if(stmt.type==="ContentStatement"){result+=stmt.value}else if(stmt.type==="MustacheStatement"){const value=resolveExpression(stmt.path,data,identifierData);if(value!=null){result+=String(value)}}}return result}function resolveExpression(expr,data,identifierData,helpers){if((0,_parserts.isThisExpression)(expr)){return data}if(expr.type==="StringLiteral")return expr.value;if(expr.type==="NumberLiteral")return expr.value;if(expr.type==="BooleanLiteral")return expr.value;if(expr.type==="NullLiteral")return null;if(expr.type==="UndefinedLiteral")return undefined;if(expr.type==="SubExpression"){const subExpr=expr;if(subExpr.path.type==="PathExpression"){const helperName=subExpr.path.original;const helper=helpers?.get(helperName);if(helper){const isMap=helperName===_maphelpersts.MapHelpers.MAP_HELPER_NAME;const resolvedArgs=[];for(let i=0;i<subExpr.params.length;i++){const param=subExpr.params[i];if(isMap&&i===1&&param.type==="StringLiteral"){resolvedArgs.push(param.value)}else{resolvedArgs.push(resolveExpression(param,data,identifierData,helpers))}}return helper.fn(...resolvedArgs)}}return undefined}const segments=(0,_parserts.extractPathSegments)(expr);if(segments.length===0){throw new _errorsts.TemplateRuntimeError(`Cannot resolve expression of type "${expr.type}"`)}const{cleanSegments,identifier}=(0,_parserts.extractExpressionIdentifier)(segments);if((0,_parserts.isRootPathTraversal)(cleanSegments)){return undefined}if((0,_parserts.isRootSegments)(cleanSegments)){if(identifier!==null&&identifierData){const source=identifierData[identifier];return source??undefined}if(identifier!==null){return undefined}return data}if(identifier!==null&&identifierData){const source=identifierData[identifier];if(source){if(Array.isArray(source)){return source.map(item=>resolveDataPath(item,cleanSegments)).filter(v=>v!==undefined)}return resolveDataPath(source,cleanSegments)}return undefined}if(identifier!==null&&!identifierData){return undefined}return resolveDataPath(data,cleanSegments)}function resolveDataPath(data,segments){let current=data;for(const segment of segments){if(current===null||current===undefined){return undefined}if(typeof current!=="object"){return undefined}current=current[segment]}return current}function mergeDataWithIdentifiers(data,identifierData){const base=data!==null&&typeof data==="object"&&!Array.isArray(data)?data:{};const merged={...base,[_parserts.ROOT_TOKEN]:data};if(!identifierData)return merged;for(const[id,idData]of Object.entries(identifierData)){merged[`${_parserts.ROOT_TOKEN}:${id}`]=idData;if(Array.isArray(idData)){continue}for(const[key,value]of Object.entries(idData)){merged[`${key}:${id}`]=value}}return merged}function renderWithHandlebars(template,data,ctx){try{if(ctx?.compiledTemplate){return ctx.compiledTemplate(data)}const cache=ctx?.compilationCache??globalCompilationCache;const hbs=ctx?.hbs??_handlebars.default;let compiled=cache.get(template);if(!compiled){compiled=hbs.compile(template,{noEscape:true,strict:false});cache.set(template,compiled)}return compiled(data)}catch(error){const message=error instanceof Error?error.message:String(error);throw new _errorsts.TemplateRuntimeError(message)}}function clearCompilationCache(){globalCompilationCache.clear()}function tryDirectBlockExecution(block,data,ctx){if(block.path.type!=="PathExpression")return undefined;const helperName=block.path.original;if(helperName!=="if"&&helperName!=="unless")return undefined;if(block.params.length!==1)return undefined;const condition=resolveExpression(block.params[0],data,ctx?.identifierData,ctx?.helpers);let isTruthy;if(Array.isArray(condition)){isTruthy=condition.length>0}else{isTruthy=!!condition}if(helperName==="unless")isTruthy=!isTruthy;const branch=isTruthy?block.program:block.inverse;if(!branch){return{value:""}}const singleExpr=(0,_parserts.getEffectivelySingleExpression)(branch);if(singleExpr){if(singleExpr.params.length===0&&!singleExpr.hash){return{value:resolveExpression(singleExpr.path,data,ctx?.identifierData,ctx?.helpers)}}if(singleExpr.params.length>0||singleExpr.hash){const directResult=tryDirectHelperExecution(singleExpr,data,ctx);if(directResult!==undefined)return directResult}}const nestedBlock=(0,_parserts.getEffectivelySingleBlock)(branch);if(nestedBlock){return tryDirectBlockExecution(nestedBlock,data,ctx)}return undefined}const DIRECT_EXECUTION_HELPERS=new Set([_maphelpersts.MapHelpers.MAP_HELPER_NAME]);function tryDirectHelperExecution(stmt,data,ctx){if(stmt.path.type!=="PathExpression")return undefined;const helperName=stmt.path.original;if(!DIRECT_EXECUTION_HELPERS.has(helperName))return undefined;const helper=ctx?.helpers?.get(helperName);if(!helper)return undefined;const isMap=helperName===_maphelpersts.MapHelpers.MAP_HELPER_NAME;const resolvedArgs=[];for(let i=0;i<stmt.params.length;i++){const param=stmt.params[i];if(isMap&&i===1){if(param.type==="StringLiteral"){resolvedArgs.push(param.value)}else{resolvedArgs.push(resolveExpression(param,data,ctx?.identifierData,ctx?.helpers))}}else{resolvedArgs.push(resolveExpression(param,data,ctx?.identifierData,ctx?.helpers))}}const value=helper.fn(...resolvedArgs);return{value}}
2
2
  //# sourceMappingURL=executor.js.map
@@ -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 { 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 { HelperDefinition, TemplateInput } 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/** Data by identifier `{ [id]: { key: value } }` */\n\tidentifierData?: Record<number, Record<string, unknown>>;\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?: Record<number, Record<string, unknown>>,\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// Render via Handlebars then attempt to coerce the result to the\n\t// detected literal type (number, boolean, null).\n\tconst singleBlock = getEffectivelySingleBlock(ast);\n\tif (singleBlock) {\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?: Record<number, Record<string, unknown>>,\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?: Record<number, Record<string, unknown>>,\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\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?: Record<number, Record<string, unknown>>,\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 object.\n\t\tmerged[`${ROOT_TOKEN}:${id}`] = idData;\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 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>([MapHelpers.MAP_HELPER_NAME]);\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":["clearCompilationCache","execute","executeFromAst","resolveDataPath","globalCompilationCache","LRUCache","template","data","identifierData","dispatchExecute","undefined","tpl","ast","parse","child","ctx","isSingleExpression","stmt","body","params","length","hash","resolveExpression","path","helpers","singleExpr","getEffectivelySingleExpression","directResult","tryDirectHelperExecution","value","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","coerceValue","coerceSchema","canUseFastPath","executeFastPath","singleBlock","getEffectivelySingleBlock","effective","getEffectiveBody","allContent","every","s","type","targetType","trimmed","trim","num","Number","isNaN","isInteger","lower","toLowerCase","coerceLiteral","result","String","expr","isThisExpression","subExpr","helperName","original","helper","get","isMap","MapHelpers","MAP_HELPER_NAME","resolvedArgs","i","param","push","fn","segments","extractPathSegments","TemplateRuntimeError","cleanSegments","identifier","extractExpressionIdentifier","isRootPathTraversal","isRootSegments","source","current","segment","base","Array","isArray","ROOT_TOKEN","id","idData","Object","entries","key","compiledTemplate","cache","compilationCache","hbs","Handlebars","compiled","compile","noEscape","strict","set","error","message","Error","clear","DIRECT_EXECUTION_HELPERS","Set","has"],"mappings":"mPAuiBgBA,+BAAAA,2BApcAC,iBAAAA,aAiCAC,wBAAAA,oBAkSAC,yBAAAA,mFAtaO,yCAES,yCACK,2CACV,oDAepB,sCAEkB,kGA4DzB,MAAMC,uBAAyB,IAAIC,iBAAQ,CAC1C,KAiBM,SAASJ,QACfK,QAAuB,CACvBC,IAAa,CACbC,cAAwD,EAExD,MAAOC,GAAAA,2BAA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,uBAAuBsG,KAAK,EAC7B,CAQA,MAAMC,yBAA2B,IAAIC,IAAY,CAAC1C,wBAAU,CAACC,eAAe,CAAC,EAY7E,SAASvC,yBACRX,IAA+B,CAC/BV,IAAa,CACbQ,GAAqB,EAGrB,GAAIE,KAAKM,IAAI,CAACsB,IAAI,GAAK,iBAAkB,OAAOnC,UAChD,MAAMmD,WAAa,AAAC5C,KAAKM,IAAI,CAA4BuC,QAAQ,CAGjE,GAAI,CAAC6C,yBAAyBE,GAAG,CAAChD,YAAa,OAAOnD,UAGtD,MAAMqD,OAAShD,KAAKS,SAASwC,IAAIH,YACjC,GAAI,CAACE,OAAQ,OAAOrD,UASpB,MAAMuD,MAAQJ,aAAeK,wBAAU,CAACC,eAAe,CAEvD,MAAMC,aAA0B,EAAE,CAClC,IAAK,IAAIC,EAAI,EAAGA,EAAIpD,KAAKE,MAAM,CAACC,MAAM,CAAEiD,IAAK,CAC5C,MAAMC,MAAQrD,KAAKE,MAAM,CAACkD,EAAE,CAI5B,GAAIJ,OAASI,IAAM,EAAG,CACrB,GAAIC,MAAMzB,IAAI,GAAK,gBAAiB,CACnCuB,aAAaG,IAAI,CAAC,AAACD,MAAgCzC,KAAK,CACzD,KAAO,CAENuC,aAAaG,IAAI,CAChBjD,kBAAkBgD,MAAO/D,KAAMQ,KAAKP,eAAgBO,KAAKS,SAE3D,CACD,KAAO,CACN4C,aAAaG,IAAI,CAChBjD,kBAAkBgD,MAAO/D,KAAMQ,KAAKP,eAAgBO,KAAKS,SAE3D,CACD,CAGA,MAAMK,MAAQkC,OAAOS,EAAE,IAAIJ,cAC3B,MAAO,CAAEvC,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 { 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>([MapHelpers.MAP_HELPER_NAME]);\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":["clearCompilationCache","execute","executeFromAst","resolveDataPath","globalCompilationCache","LRUCache","template","data","identifierData","dispatchExecute","undefined","tpl","ast","parse","child","ctx","isSingleExpression","stmt","body","params","length","hash","resolveExpression","path","helpers","singleExpr","getEffectivelySingleExpression","directResult","tryDirectHelperExecution","value","merged","mergeDataWithIdentifiers","raw","renderWithHandlebars","coerceValue","coerceSchema","canUseFastPath","executeFastPath","singleBlock","getEffectivelySingleBlock","tryDirectBlockExecution","effective","getEffectiveBody","allContent","every","s","type","targetType","trimmed","trim","num","Number","isNaN","isInteger","lower","toLowerCase","coerceLiteral","result","String","expr","isThisExpression","subExpr","helperName","original","helper","get","isMap","MapHelpers","MAP_HELPER_NAME","resolvedArgs","i","param","push","fn","segments","extractPathSegments","TemplateRuntimeError","cleanSegments","identifier","extractExpressionIdentifier","isRootPathTraversal","isRootSegments","source","Array","isArray","map","item","filter","v","current","segment","base","ROOT_TOKEN","id","idData","Object","entries","key","compiledTemplate","cache","compilationCache","hbs","Handlebars","compiled","compile","noEscape","strict","set","error","message","Error","clear","block","condition","isTruthy","branch","program","inverse","nestedBlock","DIRECT_EXECUTION_HELPERS","Set","has"],"mappings":"mPA4kBgBA,+BAAAA,2BA/dAC,iBAAAA,aAiCAC,wBAAAA,oBAkTAC,yBAAAA,mFAhcO,yCAES,yCACK,2CACV,oDAepB,sCAMkB,kGA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,MAAOhE,KAAMQ,KAAKP,eAAgBO,KAAKS,SAE3D,CACD,KAAO,CACN6C,aAAaG,IAAI,CAChBlD,kBAAkBiD,MAAOhE,KAAMQ,KAAKP,eAAgBO,KAAKS,SAE3D,CACD,CAGA,MAAMK,MAAQmC,OAAOS,EAAE,IAAIJ,cAC3B,MAAO,CAAExC,KAAM,CAChB"}
@@ -1,4 +1,4 @@
1
1
  export type { AnalyzeOptions } from "./analyzer.js";
2
2
  export * from "./errors.js";
3
3
  export { Typebars } from "./typebars.js";
4
- export { defineHelper, isArrayInput, type TemplateData, type TemplateInput, type TemplateInputArray, } from "./types.js";
4
+ export { defineHelper, type IdentifierData, type IdentifierDataEntry, isArrayInput, type TemplateData, type TemplateInput, type TemplateInputArray, } from "./types.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export type { AnalyzeOptions } from \"./analyzer\";\nexport * from \"./errors\";\nexport { Typebars } from \"./typebars\";\nexport {\n\tdefineHelper,\n\tisArrayInput,\n\ttype TemplateData,\n\ttype TemplateInput,\n\ttype TemplateInputArray,\n} from \"./types\";\n"],"names":["Typebars","defineHelper","isArrayInput"],"mappings":"mPAESA,kBAAAA,kBAAQ,MAEhBC,sBAAAA,mBAAY,MACZC,sBAAAA,mBAAY,yBAJC,6CACW,mCAOlB"}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export type { AnalyzeOptions } from \"./analyzer\";\nexport * from \"./errors\";\nexport { Typebars } from \"./typebars\";\nexport {\n\tdefineHelper,\n\ttype IdentifierData,\n\ttype IdentifierDataEntry,\n\tisArrayInput,\n\ttype TemplateData,\n\ttype TemplateInput,\n\ttype TemplateInputArray,\n} from \"./types\";\n"],"names":["Typebars","defineHelper","isArrayInput"],"mappings":"mPAESA,kBAAAA,kBAAQ,MAEhBC,sBAAAA,mBAAY,MAGZC,sBAAAA,mBAAY,yBANC,6CACW,mCASlB"}
@@ -1,5 +1,25 @@
1
1
  import type { JSONSchema7 } from "json-schema";
2
2
  import type { FromSchema, JSONSchema } from "json-schema-to-ts";
3
+ /**
4
+ * Data associated with a single template identifier.
5
+ *
6
+ * Can be a single record (scalar case) or an array of records
7
+ * (aggregated multi-version case).
8
+ */
9
+ export type IdentifierDataEntry = Record<string, unknown> | Record<string, unknown>[];
10
+ /**
11
+ * Mapping from template identifier integers to their data.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * // Scalar identifiers (standard)
16
+ * { 1: { meetingId: "abc" }, 2: { name: "Alice" } }
17
+ *
18
+ * // Aggregated identifier (multi-version node)
19
+ * { 4: [{ accountId: "A" }, { accountId: "B" }, { accountId: "C" }] }
20
+ * ```
21
+ */
22
+ export type IdentifierData = Record<number, IdentifierDataEntry>;
3
23
  /**
4
24
  * Object where each property is a `TemplateInput` (recursive).
5
25
  *
@@ -227,16 +247,28 @@ export interface CommonTypebarsOptions {
227
247
  export interface ExecuteOptions extends CommonTypebarsOptions {
228
248
  /** JSON Schema for pre-execution static validation */
229
249
  schema?: JSONSchema7;
230
- /** Data by identifier `{ [id]: { key: value } }` */
231
- identifierData?: Record<number, Record<string, unknown>>;
250
+ /**
251
+ * Data by identifier `{ [id]: { key: value } }`.
252
+ *
253
+ * Each identifier can map to a single object (standard) or an array
254
+ * of objects (aggregated multi-version data). When the value is an
255
+ * array, `{{key:N}}` extracts the property from each element.
256
+ */
257
+ identifierData?: IdentifierData;
232
258
  /** Schemas by identifier (for static validation with identifiers) */
233
259
  identifierSchemas?: Record<number, JSONSchema7>;
234
260
  }
235
261
  export interface AnalyzeAndExecuteOptions extends CommonTypebarsOptions {
236
262
  /** Schemas by identifier `{ [id]: JSONSchema7 }` for static analysis */
237
263
  identifierSchemas?: Record<number, JSONSchema7>;
238
- /** Data by identifier `{ [id]: { key: value } }` for execution */
239
- identifierData?: Record<number, Record<string, unknown>>;
264
+ /**
265
+ * Data by identifier `{ [id]: { key: value } }` for execution.
266
+ *
267
+ * Each identifier can map to a single object (standard) or an array
268
+ * of objects (aggregated multi-version data). When the value is an
269
+ * array, `{{key:N}}` extracts the property from each element.
270
+ */
271
+ identifierData?: IdentifierData;
240
272
  }
241
273
  /** Describes a parameter expected by a helper */
242
274
  export interface HelperParam {