From 084b65ff7d310406be1e1c9aedd987b058fe86f2 Mon Sep 17 00:00:00 2001 From: atinseau Date: Fri, 20 Mar 2026 23:35:05 +0100 Subject: [PATCH] feat(helpers): add array helper for constructing arrays --- src/analyzer.ts | 92 ++++++ src/executor.ts | 2 + src/helpers/array-helpers.ts | 79 +++++ src/helpers/index.ts | 1 + src/typebars.ts | 3 + tests/array-helpers.spec.ts | 547 +++++++++++++++++++++++++++++++++++ 6 files changed, 724 insertions(+) create mode 100644 src/helpers/array-helpers.ts create mode 100644 tests/array-helpers.spec.ts diff --git a/src/analyzer.ts b/src/analyzer.ts index d624ad9..d404cc8 100644 --- a/src/analyzer.ts +++ b/src/analyzer.ts @@ -8,6 +8,7 @@ import { createUnanalyzableMessage, createUnknownHelperMessage, } from "./errors"; +import { ArrayHelpers } from "./helpers/array-helpers.ts"; import { DefaultHelpers } from "./helpers/default-helpers.ts"; import { MapHelpers } from "./helpers/map-helpers.ts"; import { @@ -396,6 +397,13 @@ function processMustache( return processDefaultHelper(stmt, ctx); } + // ── Special-case: array helper ─────────────────────────────────── + // The `array` helper constructs an array from its arguments. The + // return type is `{ type: "array", items: }`. + if (helperName === ArrayHelpers.ARRAY_HELPER_NAME) { + return processArrayHelper(stmt, ctx); + } + // Check if the helper is registered const helper = ctx.helpers?.get(helperName); if (helper) { @@ -870,6 +878,85 @@ function isGuaranteedExpression( return false; } +// ─── Array Helper Analysis ────────────────────────────────────────────────── + +function processArrayHelper( + stmt: hbs.AST.MustacheStatement, + ctx: AnalysisContext, +): JSONSchema7 { + return analyzeArrayArgs(stmt.params as hbs.AST.Expression[], ctx, stmt); +} + +function processArraySubExpression( + expr: hbs.AST.SubExpression, + ctx: AnalysisContext, + parentNode?: hbs.AST.Node, +): JSONSchema7 { + return analyzeArrayArgs( + expr.params as hbs.AST.Expression[], + ctx, + parentNode ?? expr, + ); +} + +/** + * Core analysis logic for the `array` helper (shared by Mustache and + * SubExpression paths). + * + * 1. Validates argument count (≥ 1) + * 2. Resolves the schema of each argument + * 3. Returns `{ type: "array", items: }` + * + * Unlike `default`, there is no type compatibility check between arguments: + * `{{array name count}}` is valid and produces `(string | number)[]`. + */ +function analyzeArrayArgs( + params: hbs.AST.Expression[], + ctx: AnalysisContext, + node: hbs.AST.Node, +): JSONSchema7 { + const helperName = ArrayHelpers.ARRAY_HELPER_NAME; + + // ── 1. Check argument count ────────────────────────────────────────── + if (params.length < 1) { + addDiagnostic( + ctx, + "MISSING_ARGUMENT", + "error", + `Helper "${helperName}" expects at least 1 argument(s), but got 0`, + node, + { + helperName, + expected: "1 argument(s)", + actual: "0 argument(s)", + }, + ); + return { type: "array" }; + } + + // ── 2. Resolve the schema of each argument ─────────────────────────── + const resolvedSchemas: JSONSchema7[] = []; + + for (let i = 0; i < params.length; i++) { + const param = params[i] as hbs.AST.Expression; + const resolvedSchema = resolveExpressionWithDiagnostics(param, ctx, node); + + if (resolvedSchema) { + resolvedSchemas.push(resolvedSchema); + } + } + + // ── 3. Build output schema ─────────────────────────────────────────── + if (resolvedSchemas.length === 0) return { type: "array" }; + + const itemSchema = + resolvedSchemas.length === 1 + ? (resolvedSchemas[0] as JSONSchema7) + : simplifySchema({ oneOf: resolvedSchemas }); + + return { type: "array", items: itemSchema }; +} + /** * Checks whether a resolved type is compatible with the type expected * by a helper parameter. @@ -1621,6 +1708,11 @@ function resolveSubExpression( return processDefaultSubExpression(expr, ctx, parentNode); } + // ── Special-case: array helper ─────────────────────────────────── + if (helperName === ArrayHelpers.ARRAY_HELPER_NAME) { + return processArraySubExpression(expr, ctx, parentNode); + } + const helper = ctx.helpers?.get(helperName); if (!helper) { addDiagnostic( diff --git a/src/executor.ts b/src/executor.ts index d51897c..87f31bb 100644 --- a/src/executor.ts +++ b/src/executor.ts @@ -2,6 +2,7 @@ import Handlebars from "handlebars"; import type { JSONSchema7 } from "json-schema"; import { dispatchExecute } from "./dispatch.ts"; import { TemplateRuntimeError } from "./errors.ts"; +import { ArrayHelpers } from "./helpers/array-helpers.ts"; import { DefaultHelpers } from "./helpers/default-helpers.ts"; import { MapHelpers } from "./helpers/map-helpers.ts"; import { @@ -676,6 +677,7 @@ function tryDirectBlockExecution( /** Set of helper names that must be executed directly (bypass Handlebars) */ const DIRECT_EXECUTION_HELPERS = new Set([ + ArrayHelpers.ARRAY_HELPER_NAME, DefaultHelpers.DEFAULT_HELPER_NAME, MapHelpers.MAP_HELPER_NAME, ]); diff --git a/src/helpers/array-helpers.ts b/src/helpers/array-helpers.ts new file mode 100644 index 0000000..7429f5d --- /dev/null +++ b/src/helpers/array-helpers.ts @@ -0,0 +1,79 @@ +import type { HelperDefinition } from "../types.ts"; +import { HelperFactory } from "./helper-factory.ts"; + +// ─── ArrayHelpers ─────────────────────────────────────────────────────────── +// Provides a variadic helper that constructs an array from its arguments. +// +// - **`array`** — Collects all arguments into a single array. +// Usage: `{{ array name status }}` +// `{{ array "a" "b" "c" }}` +// `{{ array (add count 1) 42 }}` +// +// ─── Registration ──────────────────────────────────────────────────────────── +// ArrayHelpers are automatically pre-registered by the `Typebars` +// constructor. They can also be registered manually on any object +// implementing `HelperRegistry`: +// +// const factory = new ArrayHelpers(); +// factory.register(engine); // registers all helpers +// factory.unregister(engine); // removes all helpers +// +// ─── Static Analysis ───────────────────────────────────────────────────────── +// The `array` helper has special static analysis handling in the analyzer: +// - At least 1 argument is required +// - All arguments must have compatible types +// - The inferred return type is `{ type: "array", items: }` + +// ─── Internal utilities ───────────────────────────────────────────────────── + +/** + * Checks whether a value is a Handlebars options object. + * Handlebars always passes an options object as the last argument to helpers. + */ +function isHandlebarsOptions(value: unknown): boolean { + return ( + value !== null && + typeof value === "object" && + "hash" in (value as Record) && + "name" in (value as Record) + ); +} + +/** + * Collects all arguments into an array. + * The trailing Handlebars options object is automatically excluded. + */ +function arrayValue(...args: unknown[]): unknown[] { + return args.filter((a) => !isHandlebarsOptions(a)); +} + +// ─── Main class ───────────────────────────────────────────────────────────── + +export class ArrayHelpers extends HelperFactory { + /** The name used for special-case detection in the analyzer/executor */ + static readonly ARRAY_HELPER_NAME = "array"; + + // ─── buildDefinitions (required by HelperFactory) ────────────────── + + protected buildDefinitions(defs: Map): void { + this.registerArray(defs); + } + + // ── array ────────────────────────────────────────────────────────── + + /** Registers the `array` helper */ + private registerArray(defs: Map): void { + defs.set(ArrayHelpers.ARRAY_HELPER_NAME, { + fn: arrayValue, + params: [ + { + name: "values", + description: "One or more values to collect into an array (variadic)", + }, + ], + // No static returnType — the analyzer infers it from the arguments + description: + "Constructs an array from its arguments: {{ array name status }}", + }); + } +} diff --git a/src/helpers/index.ts b/src/helpers/index.ts index 0e62a12..7620f97 100644 --- a/src/helpers/index.ts +++ b/src/helpers/index.ts @@ -1,3 +1,4 @@ +export { ArrayHelpers } from "./array-helpers"; export { DefaultHelpers } from "./default-helpers"; export { HelperFactory, type HelperRegistry } from "./helper-factory"; export { LogicalHelpers } from "./logical-helpers"; diff --git a/src/typebars.ts b/src/typebars.ts index 3585591..04a2464 100644 --- a/src/typebars.ts +++ b/src/typebars.ts @@ -14,6 +14,7 @@ import { import { TemplateAnalysisError } from "./errors.ts"; import { executeFromAst } from "./executor.ts"; import { + ArrayHelpers, DefaultHelpers, LogicalHelpers, MapHelpers, @@ -66,6 +67,7 @@ import { LRUCache } from "./utils"; // In single-expression mode the executor bypasses Handlebars entirely, so the // raw value is preserved. const DIRECT_EXECUTION_HELPER_NAMES = new Set([ + ArrayHelpers.ARRAY_HELPER_NAME, MapHelpers.MAP_HELPER_NAME, ]); @@ -115,6 +117,7 @@ export class Typebars { this.compilationCache = new LRUCache(options.compilationCacheSize ?? 256); // ── Built-in helpers ───────────────────────────────────────────── + new ArrayHelpers().register(this); new MathHelpers().register(this); new LogicalHelpers().register(this); new MapHelpers().register(this); diff --git a/tests/array-helpers.spec.ts b/tests/array-helpers.spec.ts new file mode 100644 index 0000000..90605bb --- /dev/null +++ b/tests/array-helpers.spec.ts @@ -0,0 +1,547 @@ +import { describe, expect, test } from "bun:test"; +import type { JSONSchema7 } from "json-schema"; +import { Typebars } from "../src/typebars.ts"; + +// ─── array helper tests ───────────────────────────────────────────────────── + +const engine = new Typebars(); + +// ─── Schema with various types ────────────────────────────────────────────── + +const testSchema: JSONSchema7 = { + type: "object", + properties: { + name: { type: "string" }, + status: { type: "string" }, + count: { type: "number" }, + score: { type: "number" }, + active: { type: "boolean" }, + tags: { type: "array", items: { type: "string" } }, + }, + required: ["name", "count"], +}; + +const testData = { + name: "Alice", + status: "active", + count: 42, + score: 9.5, + active: true, + tags: ["dev", "admin"], +}; + +// ─── Analysis ─────────────────────────────────────────────────────────────── + +describe("array helper — analysis", () => { + test("valid: string args → string array", () => { + const result = engine.analyze("{{array name status}}", testSchema); + expect(result.valid).toBe(true); + expect( + result.diagnostics.filter((d) => d.severity === "error"), + ).toHaveLength(0); + }); + + test("valid: number args → number array", () => { + const result = engine.analyze("{{array count score}}", testSchema); + expect(result.valid).toBe(true); + expect( + result.diagnostics.filter((d) => d.severity === "error"), + ).toHaveLength(0); + }); + + test("valid: single argument", () => { + const result = engine.analyze("{{array name}}", testSchema); + expect(result.valid).toBe(true); + expect( + result.diagnostics.filter((d) => d.severity === "error"), + ).toHaveLength(0); + }); + + test("valid: string literal arguments", () => { + const result = engine.analyze('{{array "a" "b" "c"}}', testSchema); + expect(result.valid).toBe(true); + }); + + test("valid: number literal arguments", () => { + const result = engine.analyze("{{array 1 2 3}}", testSchema); + expect(result.valid).toBe(true); + }); + + test("valid: sub-expression arguments", () => { + const result = engine.analyze("{{array (add count 1) 42}}", testSchema); + expect(result.valid).toBe(true); + }); + + test("valid: mixed expression and literal of same type", () => { + const result = engine.analyze('{{array name "fallback"}}', testSchema); + expect(result.valid).toBe(true); + }); + + test("valid: identifier syntax", () => { + const identifierSchemas = { + 1: { + type: "object" as const, + properties: { score: { type: "number" as const } }, + required: ["score"], + }, + }; + const result = engine.analyze("{{array count score:1}}", testSchema, { + identifierSchemas, + }); + expect(result.valid).toBe(true); + }); + + test("error: no arguments", () => { + // Without args, Handlebars parses "array" as a simple expression, not a helper. + // It tries to resolve "array" as a property in the schema → PROPERTY_NOT_FOUND. + const result = engine.analyze("{{array}}", testSchema); + expect(result.valid).toBe(false); + }); + + test("valid: mixed types (string + number) → heterogeneous array", () => { + const result = engine.analyze("{{array name count}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema?.type).toBe("array"); + }); + + test("valid: mixed types (string + boolean) → heterogeneous array", () => { + const result = engine.analyze("{{array name active}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema?.type).toBe("array"); + }); + + // ── Output schema inference ────────────────────────────────────────── + + test("output schema: string args → { type: array, items: string }", () => { + const result = engine.analyze("{{array name status}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "string" }, + }); + }); + + test("output schema: number args → { type: array, items: number }", () => { + const result = engine.analyze("{{array count score}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "number" }, + }); + }); + + test("output schema: single string arg → { type: array, items: string }", () => { + const result = engine.analyze("{{array name}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "string" }, + }); + }); + + test("output schema: literal strings → { type: array, items: string }", () => { + const result = engine.analyze('{{array "a" "b"}}', testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "string" }, + }); + }); + + test("output schema: number literals → { type: array, items: number }", () => { + const result = engine.analyze("{{array 1 2 3}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "number" }, + }); + }); + + test("output schema: sub-expression result → number array", () => { + const result = engine.analyze("{{array (add count 1) 42}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "number" }, + }); + }); +}); + +// ─── Sub-expression analysis ──────────────────────────────────────────────── + +describe("array helper — sub-expression analysis", () => { + test("valid: array as sub-expression in if block", () => { + const result = engine.analyze( + '{{#if (array name "test")}}has value{{/if}}', + testSchema, + ); + expect(result.valid).toBe(true); + }); + + test("valid: sub-expression with mixed types", () => { + const result = engine.analyze( + "{{#if (array name count)}}has value{{/if}}", + testSchema, + ); + expect(result.valid).toBe(true); + }); +}); + +// ─── Execution ────────────────────────────────────────────────────────────── + +describe("array helper — execution", () => { + test("returns array of resolved string values", () => { + const result = engine.execute("{{array name status}}", testData); + expect(result).toEqual(["Alice", "active"]); + }); + + test("returns array of resolved number values", () => { + const result = engine.execute("{{array count score}}", testData); + expect(result).toEqual([42, 9.5]); + }); + + test("returns array with literal string values", () => { + const result = engine.execute('{{array "a" "b" "c"}}', testData); + expect(result).toEqual(["a", "b", "c"]); + }); + + test("returns array with literal number values", () => { + const result = engine.execute("{{array 1 2 3}}", testData); + expect(result).toEqual([1, 2, 3]); + }); + + test("returns array with sub-expression results", () => { + const result = engine.execute("{{array (add count 1) 42}}", testData); + expect(result).toEqual([43, 42]); + }); + + test("returns array with single element", () => { + const result = engine.execute("{{array name}}", testData); + expect(result).toEqual(["Alice"]); + }); + + test("returns array with mixed expressions and literals", () => { + const result = engine.execute('{{array name "Bob"}}', testData); + expect(result).toEqual(["Alice", "Bob"]); + }); + + test("handles undefined values (optional properties)", () => { + const result = engine.execute("{{array name status}}", { + name: "Alice", + }); + expect(result).toEqual(["Alice", undefined]); + }); +}); + +// ─── Integration with object templates ────────────────────────────────────── + +describe("array helper — object template integration", () => { + test("valid: array helper in array-typed property", () => { + const coerceSchema: JSONSchema7 = { + type: "object", + properties: { + items: { type: "array", items: { type: "string" } }, + }, + }; + const result = engine.analyze( + { items: "{{array name status}}" }, + testSchema, + { coerceSchema }, + ); + expect(result.valid).toBe(true); + }); + + test("execution: array helper in object template", () => { + const result = engine.execute({ items: "{{array name status}}" }, testData); + expect(result).toEqual({ items: ["Alice", "active"] }); + }); + + test("execution: array helper with numbers in object template", () => { + const result = engine.execute( + { scores: "{{array count score}}" }, + testData, + ); + expect(result).toEqual({ scores: [42, 9.5] }); + }); + + test("execution: array helper with sub-expressions in object template", () => { + const result = engine.execute( + { values: "{{array (add count 1) 42}}" }, + testData, + ); + expect(result).toEqual({ values: [43, 42] }); + }); +}); + +// ─── Exotic / edge-case tests ─────────────────────────────────────────────── + +describe("array helper — nested object templates", () => { + test("execution: array in deeply nested object", () => { + const result = engine.execute( + { + level1: { + level2: { + tags: "{{array name status}}", + }, + }, + }, + testData, + ); + expect(result).toEqual({ + level1: { + level2: { + tags: ["Alice", "active"], + }, + }, + }); + }); + + test("execution: multiple array helpers in sibling properties", () => { + const result = engine.execute( + { + names: "{{array name status}}", + numbers: "{{array count score}}", + }, + testData, + ); + expect(result).toEqual({ + names: ["Alice", "active"], + numbers: [42, 9.5], + }); + }); + + test("execution: array helper alongside regular templates in nested object", () => { + const result = engine.execute( + { + info: { + label: "{{name}}", + tags: '{{array name "extra"}}', + count: "{{count}}", + }, + }, + testData, + ); + expect(result).toEqual({ + info: { + label: "Alice", + tags: ["Alice", "extra"], + count: 42, + }, + }); + }); + + test("execution: array helper at multiple nesting levels", () => { + const result = engine.execute( + { + topTags: "{{array name status}}", + nested: { + innerTags: '{{array "x" "y" "z"}}', + }, + }, + testData, + ); + expect(result).toEqual({ + topTags: ["Alice", "active"], + nested: { + innerTags: ["x", "y", "z"], + }, + }); + }); + + test("execution: array inside a 3-level deep object", () => { + const result = engine.execute( + { + a: { + b: { + c: { + values: "{{array count score}}", + }, + }, + }, + }, + testData, + ); + const a = result as Record; + const b = (a.a as Record).b as Record; + const c = b.c as Record; + expect(c.values).toEqual([42, 9.5]); + expect(Array.isArray(c.values)).toBe(true); + }); +}); + +describe("array helper — output schema with mixed / union types", () => { + test("output schema: number + string args → oneOf union in items", () => { + // Uses a permissive schema where the property has no type constraint + const permissiveSchema: JSONSchema7 = { + type: "object", + properties: { + a: {}, + b: {}, + }, + required: ["a", "b"], + }; + const result = engine.analyze("{{array a b}}", permissiveSchema); + // Both args have no type info → should be valid (no type to compare) + expect(result.valid).toBe(true); + expect(result.outputSchema?.type).toBe("array"); + }); + + test("output schema: integer is compatible with number", () => { + const schemaWithInteger: JSONSchema7 = { + type: "object", + properties: { + intVal: { type: "integer" }, + numVal: { type: "number" }, + }, + required: ["intVal", "numVal"], + }; + const result = engine.analyze("{{array intVal numVal}}", schemaWithInteger); + // integer is compatible with number + expect(result.valid).toBe(true); + expect(result.outputSchema?.type).toBe("array"); + }); + + test("output schema: number literal + number expression → number items", () => { + const result = engine.analyze("{{array count 100}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "number" }, + }); + }); + + test("output schema: string + number → oneOf union in items", () => { + const result = engine.analyze("{{array name count}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { oneOf: [{ type: "string" }, { type: "number" }] }, + }); + }); + + test("output schema: string + boolean → oneOf union in items", () => { + const result = engine.analyze("{{array name active}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { oneOf: [{ type: "string" }, { type: "boolean" }] }, + }); + }); + + test("output schema: string + number + boolean → oneOf union in items", () => { + const result = engine.analyze("{{array name count active}}", testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { + oneOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }], + }, + }); + }); +}); + +describe("array helper — conditional blocks (#if)", () => { + test("execution: array in #if true branch", () => { + const result = engine.execute( + "{{#if active}}{{array name status}}{{/if}}", + testData, + ); + expect(result).toEqual(["Alice", "active"]); + }); + + test("execution: array in #if false branch → empty string", () => { + const result = engine.execute( + "{{#if active}}{{array name status}}{{/if}}", + { active: false, name: "Alice", status: "active" }, + ); + expect(result).toBe(""); + }); + + test("execution: array in #if else branch", () => { + const result = engine.execute( + '{{#if active}}{{array name status}}{{else}}{{array "none"}}{{/if}}', + { active: false, name: "Alice", status: "active" }, + ); + expect(result).toEqual(["none"]); + }); +}); + +describe("array helper — many arguments", () => { + test("execution: 5+ arguments", () => { + const result = engine.execute('{{array "a" "b" "c" "d" "e" "f"}}', {}); + expect(result).toEqual(["a", "b", "c", "d", "e", "f"]); + }); + + test("analysis: 5+ literal arguments → valid", () => { + const result = engine.analyze('{{array "a" "b" "c" "d" "e"}}', testSchema); + expect(result.valid).toBe(true); + expect(result.outputSchema).toEqual({ + type: "array", + items: { type: "string" }, + }); + }); +}); + +describe("array helper — analyzeAndExecute", () => { + test("nested object with array helper → analysis valid + execution returns array", () => { + const { analysis, value } = engine.analyzeAndExecute( + { + meta: { + tags: "{{array name status}}", + }, + }, + testSchema, + testData, + ); + expect(analysis.valid).toBe(true); + expect(value).toEqual({ + meta: { + tags: ["Alice", "active"], + }, + }); + const tags = ( + (value as Record).meta as Record + ).tags; + expect(Array.isArray(tags)).toBe(true); + }); + + test("analyzeAndExecute: mixed types → valid with heterogeneous array", () => { + const { analysis, value } = engine.analyzeAndExecute( + { items: "{{array name count}}" }, + testSchema, + testData, + ); + expect(analysis.valid).toBe(true); + expect(value).toEqual({ items: ["Alice", 42] }); + }); +}); + +describe("array helper — compiled template", () => { + test("compiled template preserves array in nested object", () => { + const compiled = engine.compile({ + data: { + ids: "{{array name status}}", + }, + }); + const result = compiled.execute(testData); + expect(result).toEqual({ + data: { + ids: ["Alice", "active"], + }, + }); + const ids = ( + (result as Record).data as Record + ).ids; + expect(Array.isArray(ids)).toBe(true); + }); + + test("compiled template: array with sub-expressions", () => { + const compiled = engine.compile({ + values: "{{array (add count 1) score}}", + }); + const result = compiled.execute(testData); + expect(result).toEqual({ + values: [43, 9.5], + }); + }); +});