Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions src/analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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: <union of arg types> }`.
if (helperName === ArrayHelpers.ARRAY_HELPER_NAME) {
return processArrayHelper(stmt, ctx);
}

// Check if the helper is registered
const helper = ctx.helpers?.get(helperName);
if (helper) {
Expand Down Expand Up @@ -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: <union of arg types> }`
*
* 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.
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 2 additions & 0 deletions src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -676,6 +677,7 @@ function tryDirectBlockExecution(

/** Set of helper names that must be executed directly (bypass Handlebars) */
const DIRECT_EXECUTION_HELPERS = new Set<string>([
ArrayHelpers.ARRAY_HELPER_NAME,
DefaultHelpers.DEFAULT_HELPER_NAME,
MapHelpers.MAP_HELPER_NAME,
]);
Expand Down
79 changes: 79 additions & 0 deletions src/helpers/array-helpers.ts
Original file line number Diff line number Diff line change
@@ -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: <union of arg types> }`

// ─── 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<string, unknown>) &&
"name" in (value as Record<string, unknown>)
);
}

/**
* 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<string, HelperDefinition>): void {
this.registerArray(defs);
}

// ── array ──────────────────────────────────────────────────────────

/** Registers the `array` helper */
private registerArray(defs: Map<string, HelperDefinition>): 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 }}",
});
}
}
1 change: 1 addition & 0 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
3 changes: 3 additions & 0 deletions src/typebars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import { TemplateAnalysisError } from "./errors.ts";
import { executeFromAst } from "./executor.ts";
import {
ArrayHelpers,
DefaultHelpers,
LogicalHelpers,
MapHelpers,
Expand Down Expand Up @@ -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<string>([
ArrayHelpers.ARRAY_HELPER_NAME,
MapHelpers.MAP_HELPER_NAME,
]);

Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading