perf(bundle): lazy-load the nunjucks template engine (#2535)

Closes #2531.

## Summary

The full `nunjucks` templating engine (~226KB) plus `ha-nunjucks`
(~46KB) — roughly **272KB, ~13% of the eager entry chunk** — was
statically imported and downloaded by every card on initial load, even
though templates only apply when a config value contains a `{{ … }}` /
`{% … %}` delimiter. Most cards use no templates and never need the
engine.

This defers the engine behind a dynamic `import('ha-nunjucks/dist')` so
it ships in a separate, on-demand chunk instead of the eager
`card-*.js`.

## Approach

The render path (`TemplateRenderer.renderRecursively`) is **kept
synchronous** — it is called from many synchronous hot paths
(condition/trigger evaluators, picture-elements rendering, actions,
folder matchers), and making it async would be a large, high-risk
refactor of the evaluation core.

Instead:

- **New `src/card-controller/templates/engine.ts`** — a module-level
singleton lazy loader (`loadTemplateEngine()` / `getTemplateEngine()`)
shared across all `TemplateRenderer` instances, plus a
`containsTemplate()` delimiter helper.
- **Delimiter gating** — strings without a delimiter never touch the
engine (the overwhelming majority of renders).
- **Pre-warm at config time** — because every template string originates
in the config, a new mandatory `TEMPLATE_ENGINE` initialization aspect
loads the engine before first render whenever the config contains a
delimiter. This **guarantees no raw `{{ … }}` flash**: content/condition
rendering is blocked until the engine is present for template-using
cards. Cards without templates never load it.

## Result

- nunjucks + ha-nunjucks move out of the eager chunk into a separate
chunk fetched only when a card actually uses templates.
- No change to the synchronous public render API; condition/trigger
evaluation core untouched.

## Tests

- New `engine.ts` loader coverage (concurrent load, cached reuse,
not-loaded fallback).
- The 11 existing test files that render real (delimiter-bearing)
templates declare their dependency explicitly via
`beforeAll(loadTemplateEngine)` — no global/implicit setup hook.
- Full suite green (4764 tests), lint and ts-prune clean, per-file 100%
coverage maintained for the affected directories.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c

---
_Generated by [Claude
Code](https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c)_
This commit is contained in:
Dermot Duffy
2026-06-30 17:45:13 -07:00
committed by dermotduffy
parent b33c034810
commit ea251ca988
59 changed files with 1420 additions and 541 deletions
@@ -1,8 +1,17 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { TemplateManager } from '../../../src/card-controller/templates';
import { ConditionsManager } from '../../../src/condition-trigger/conditions/conditions-manager';
import { ConditionStateManager } from '../../../src/condition-trigger/conditions/state-manager';
import { createHASS, createStateEntity } from '../../test-utils';
import {
createHASS,
createMockTemplateRenderer,
createStateEntity,
} from '../../test-utils';
// A mock renderer for the orchestration tests, which never render templates.
// The `enabled` template suite below uses its own real, loaded engine.
const templateManager = createMockTemplateRenderer();
// Per-condition-type evaluation is covered by tests/conditions/conditions/<type>.test.ts.
// This file covers the manager's own orchestration: building/destroying evaluators,
@@ -23,6 +32,7 @@ describe('ConditionsManager', () => {
fullscreen: true,
},
],
templateManager,
stateManager,
);
@@ -40,6 +50,7 @@ describe('ConditionsManager', () => {
const stateManager = new ConditionStateManager();
const manager = new ConditionsManager(
[{ condition: 'fullscreen' as const, fullscreen: true }],
templateManager,
stateManager,
);
@@ -71,9 +82,10 @@ describe('ConditionsManager', () => {
matches: true,
} as unknown as MediaQueryList);
const manager = new ConditionsManager([
{ condition: 'screen' as const, media_query: 'whatever' },
]);
const manager = new ConditionsManager(
[{ condition: 'screen' as const, media_query: 'whatever' }],
templateManager,
);
const listener = vi.fn();
manager.addListener(listener);
@@ -92,6 +104,7 @@ describe('ConditionsManager', () => {
const stateManager = new ConditionStateManager();
const manager = new ConditionsManager(
[{ condition: 'fullscreen' as const, fullscreen: true }],
templateManager,
stateManager,
);
@@ -120,6 +133,7 @@ describe('ConditionsManager', () => {
const stateManager = new ConditionStateManager();
const manager = new ConditionsManager(
[{ condition: 'fullscreen' as const, fullscreen: true }],
templateManager,
stateManager,
);
@@ -136,6 +150,7 @@ describe('ConditionsManager', () => {
const stateManager = new ConditionStateManager();
const manager = new ConditionsManager(
[{ condition: 'fullscreen' as const, fullscreen: true }],
templateManager,
stateManager,
);
@@ -152,6 +167,7 @@ describe('ConditionsManager', () => {
const stateManager = new ConditionStateManager();
const manager = new ConditionsManager(
[{ condition: 'view' as const, views: ['live'] }],
templateManager,
stateManager,
);
@@ -178,10 +194,18 @@ describe('ConditionsManager', () => {
describe('enabled', () => {
const ENABLED_TEMPLATE = '{{ is_state("binary_sensor.flag", "on") }}';
// These cases gate on a rendered `enabled` template, so use a real engine
// loaded for the synchronous renderer (rather than the shared mock).
const templateManager = new TemplateManager();
beforeAll(async () => {
await templateManager.loadRenderer();
});
it('should ignore a disabled condition', () => {
const stateManager = new ConditionStateManager();
const manager = new ConditionsManager(
[{ condition: 'fullscreen' as const, fullscreen: true, enabled: false }],
templateManager,
stateManager,
);
@@ -196,6 +220,7 @@ describe('ConditionsManager', () => {
const stateManager = new ConditionStateManager();
const manager = new ConditionsManager(
[{ condition: 'fullscreen' as const, fullscreen: true, enabled: true }],
templateManager,
stateManager,
);
@@ -219,6 +244,7 @@ describe('ConditionsManager', () => {
enabled: ENABLED_TEMPLATE,
},
],
templateManager,
stateManager,
);
@@ -240,6 +266,7 @@ describe('ConditionsManager', () => {
enabled: ENABLED_TEMPLATE,
},
],
templateManager,
stateManager,
);
@@ -258,6 +285,7 @@ describe('ConditionsManager', () => {
enabled: ENABLED_TEMPLATE,
},
],
templateManager,
stateManager,
);
@@ -282,6 +310,7 @@ describe('ConditionsManager', () => {
enabled: ENABLED_TEMPLATE,
},
],
templateManager,
stateManager,
);
@@ -1,7 +1,12 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { TemplateManager } from '../../../../src/card-controller/templates';
import { createConditionEvaluator } from '../../../../src/condition-trigger/conditions/factory';
import { createHASS, createStateEntity } from '../../../test-utils';
import {
createHASS,
createMockTemplateRenderer,
createStateEntity,
} from '../../../test-utils';
import { createEvaluatorContext } from './test-utils';
// @vitest-environment jsdom
@@ -122,7 +127,12 @@ describe('numeric state condition', () => {
).toBeFalsy();
});
it('should compare the rendered value_template instead of the state', () => {
it('should compare the rendered value_template instead of the state', async () => {
// This case renders a real value_template, so load the lazily-imported
// engine for the synchronous renderer.
const templateManager = new TemplateManager();
await templateManager.loadRenderer();
const evaluator = createConditionEvaluator(
{
condition: 'numeric_state' as const,
@@ -130,7 +140,7 @@ describe('numeric state condition', () => {
value_template: '{{ 11 }}',
above: 10,
},
createEvaluatorContext(),
createEvaluatorContext({ templateRenderer: templateManager }),
);
// The entity state (0) would fail; the template value (11) passes.
@@ -141,6 +151,28 @@ describe('numeric state condition', () => {
).toBeTruthy();
});
it('should not match a value_template until the renderer has loaded', () => {
const unloadedRenderer = createMockTemplateRenderer();
vi.mocked(unloadedRenderer).isLoaded.mockReturnValue(false);
const evaluator = createConditionEvaluator(
{
condition: 'numeric_state' as const,
entity_id: 'sensor.foo',
value_template: '{{ 11 }}',
above: 10,
},
createEvaluatorContext({ templateRenderer: unloadedRenderer }),
);
// The entity state (11) would pass, but the value_template cannot be
// evaluated before the renderer loads, so the condition does not match.
expect(
evaluator.evaluate({
hass: createHASS({ 'sensor.foo': createStateEntity({ state: '11' }) }),
}).result,
).toBeFalsy();
});
it('should not match when the value is not numeric', () => {
const evaluator = createConditionEvaluator(
{ condition: 'numeric_state' as const, entity_id: 'sensor.foo', above: 10 },
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TemplateManager } from '../../../../src/card-controller/templates';
import { createConditionEvaluator } from '../../../../src/condition-trigger/conditions/factory';
import { createHASS, createStateEntity } from '../../../test-utils';
import { createEvaluatorContext } from './test-utils';
@@ -335,7 +336,12 @@ describe('state condition', () => {
).toBeTruthy();
});
it('should render a templated "for" before comparing', () => {
it('should render a templated "for" before comparing', async () => {
// This case renders a real templated `for`, so load the lazily-imported
// engine for the synchronous renderer.
const templateManager = new TemplateManager();
await templateManager.loadRenderer();
const evaluator = createConditionEvaluator(
{
condition: 'state' as const,
@@ -343,7 +349,7 @@ describe('state condition', () => {
state: 'on',
for: "{{ states('input_number.delay') }}",
},
createEvaluatorContext(),
createEvaluatorContext({ templateRenderer: templateManager }),
);
const evaluateHeldSince = (lastChanged: string): boolean =>
@@ -1,18 +1,24 @@
import { describe, expect, it } from 'vitest';
import { beforeAll, describe, expect, it } from 'vitest';
import { TemplateManager } from '../../../../src/card-controller/templates';
import { createConditionEvaluator } from '../../../../src/condition-trigger/conditions/factory';
import { createHASS, createStateEntity } from '../../../test-utils';
import { createEvaluatorContext } from './test-utils';
// @vitest-environment jsdom
describe('template condition', () => {
const templateManager = new TemplateManager();
beforeAll(async () => {
await templateManager.loadRenderer();
});
it('should evaluate true when template evalutes to true', () => {
const evaluator = createConditionEvaluator(
{
condition: 'template' as const,
value_template: '{{ is_state("sensor.foo", "on") }}',
},
createEvaluatorContext(),
createEvaluatorContext({ templateRenderer: templateManager }),
);
expect(evaluator.evaluate({}).result).toBeFalsy();
@@ -35,7 +41,7 @@ describe('template condition', () => {
// This does not result in a boolean.
value_template: '{{ hass.states["light.office"].state }}',
},
createEvaluatorContext(),
createEvaluatorContext({ templateRenderer: templateManager }),
);
expect(
@@ -48,7 +54,7 @@ describe('template condition', () => {
it('should accept a template rendering the string "true" for HA symmetry', () => {
const evaluator = createConditionEvaluator(
{ condition: 'template' as const, value_template: '{{ "true" }}' },
createEvaluatorContext(),
createEvaluatorContext({ templateRenderer: templateManager }),
);
expect(evaluator.evaluate({ hass: createHASS({}) }).result).toBeTruthy();
@@ -1,6 +1,9 @@
import { TemplateRenderer } from '../../../../src/card-controller/templates';
import type { EvaluatorContext } from '../../../../src/condition-trigger/conditions/conditions/types';
import { createMockTemplateRenderer } from '../../../test-utils';
export const createEvaluatorContext = (): EvaluatorContext => ({
templateRenderer: new TemplateRenderer(),
export const createEvaluatorContext = (
context?: Partial<EvaluatorContext>,
): EvaluatorContext => ({
templateRenderer: createMockTemplateRenderer(),
...context,
});