Files
advanced-camera-card/src/condition-trigger/triggers/manager.ts
T
Dermot Duffy ea251ca988 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)_
2026-06-30 17:45:13 -07:00

99 lines
3.0 KiB
TypeScript

import type { HASSManagerReadonlyInterface } from '../../card-controller/hass/types';
import type { TemplateRenderer } from '../../card-controller/templates';
import type { Trigger } from '../../config/schema/condition-trigger/triggers/types';
import { isEnabled } from '../common/is-enabled';
import type { ConditionStateManagerReadonlyInterface } from '../conditions/types';
import { createTriggerEvaluator } from './factory';
import type {
TriggerCallback,
TriggerEvaluator,
TriggerEvaluatorContext,
} from './triggers/types';
import type { TriggerData } from './types';
// A trigger evaluator paired with its config, so `enabled` can be re-checked
// against the config each time the evaluator triggers.
interface ManagedTrigger {
config: Trigger;
evaluator: TriggerEvaluator;
}
/**
* Orchestrates an array of triggers (e.g. for one automation) and notifies
* listeners whenever ANY of them triggers (the top-level triggers list is an
* implicit OR). This is the push-based sibling of `ConditionsManager`.
*/
export class TriggersManager {
private _context: TriggerEvaluatorContext;
private _triggers: ManagedTrigger[];
private _listeners: TriggerCallback[] = [];
private _subscribed = false;
constructor(
triggers: Trigger[],
stateManager: ConditionStateManagerReadonlyInterface,
hassManager: HASSManagerReadonlyInterface,
templateRenderer: TemplateRenderer,
) {
this._context = {
stateManager,
templateRenderer,
hassManager,
};
this._triggers = triggers.map((config) => ({
config,
evaluator: createTriggerEvaluator(config, this._context),
}));
}
/**
* Subscribe the evaluators to the state manager, establishing their
* pre-trigger baselines.
*/
public subscribe(): void {
if (this._subscribed) {
return;
}
this._subscribed = true;
this._triggers.forEach(({ config, evaluator }) =>
evaluator.subscribe((data) => {
if (
// `enabled` is a live per-trigger gate (re-evaluated each time), UNLIKE
// HA's once-at-attach: a deliberate deviation to allow dynamic triggering.
isEnabled(
this._context.templateRenderer,
config.enabled,
this._context.stateManager.getState(),
// Fail closed: with no hass the `enabled` template cannot be
// evaluated, so the trigger does not fire.
false,
)
) {
this._callListeners(data);
}
}),
);
}
public destroy(): void {
this._triggers.forEach(({ evaluator }) => evaluator.destroy());
this._triggers = [];
this._listeners = [];
}
public addListener(listener: TriggerCallback): void {
if (!this._listeners.includes(listener)) {
this._listeners.push(listener);
}
}
public removeListener(listener: TriggerCallback): void {
this._listeners = this._listeners.filter((l) => l !== listener);
}
private _callListeners = (data: TriggerData): void => {
this._listeners.forEach((listener) => listener(data));
};
}