Rule 45 - JS: Module and lifecycle shape
How a component / utility JS file is shaped internally: what the lifecycle functions are called, what an event handler is called, what tracks initialized elements, and how listeners are torn down.
Rule 41 defines the contract
between a module and the orchestrator - the IIFE, the _register
call, the init(root) / destroy(root) pair. Rule 45 defines the
shape inside that contract, so a reader who has learned one
module has learned all of them.
Rules
Module wrapper
45.1. Every component / utility JS file MUST be exactly one arrow
IIFE whose first statement is 'use strict';, matching
src/boot.js. Named-function and anonymous-function IIFEs MUST
NOT be used, and the strict directive MUST NOT be omitted.
The bundle is concatenated and shipped as a classic script, so a module without the directive runs in sloppy mode: an assignment to an undeclared name silently creates a global instead of throwing.
A module that pulls in a third-party dependency MAY carry a
leading import block above the IIFE - the bundler resolves it
before the file ships. Only the module body is constrained.
// Correct.(() => {'use strict';/* ... */})();// Wrong - named IIFE; the name describes the wrapper, not an init step.(function fooInit() {'use strict';/* ... */})();// Wrong - no strict directive; ships in sloppy mode.(() => {/* ... */})();
Lifecycle naming
45.2. The two functions passed to window.Semetrika._register(...)
MUST be named exactly init and destroy. Both take a root
and walk the subtree beneath it via window.Semetrika._collect.
Neither MUST operate on a single element.
A module that names its per-element function init and its
root-level function something else inverts the vocabulary every
other module uses, so the same identifier means "one element"
in one file and "this whole subtree" in the next.
// Correct.function init(root) {window.Semetrika._collect(root, SELECTOR).forEach(initElement);}function destroy(root) {window.Semetrika._collect(root, SELECTOR).forEach(destroyElement);}window.Semetrika._register('foo', SELECTOR, init, destroy);// Wrong - `init` takes an element, and the root walker is renamed.function init(el) {/* ... */}function publicInit(root) {window.Semetrika._collect(root, SELECTOR).forEach(init);}window.Semetrika._register('foo', SELECTOR, publicInit, publicDestroy);
45.3. Per-element lifecycle functions MUST be named
initElement(el) / destroyElement(el) in a module that manages
one kind of element, and init{Noun}(el) / destroy{Noun}(el)
per kind in a module that manages several. The two halves of a
pair MUST be symmetric.
The file name already carries the component name, so a noun on a single-element module only restates it. Where a module manages more than one kind of element - a drawer and its triggers, a dialog and its triggers, a textarea's autoresize and its counter - the noun is what tells the two apart.
setup*, bind* / unbind*, and domain-verb pairs such as
assignColor / clearColor MUST NOT be used as the per-element
entry point. Helpers called from the entry point keep whatever
descriptive name fits.
// Correct - one kind of element.function initElement(el) {/* ... */}function destroyElement(el) {/* ... */}// Correct - two kinds, each pair symmetric.function initDialog(dialog) {}function destroyDialog(dialog) {}function initTrigger(trigger) {}function destroyTrigger(trigger) {}// Wrong - asymmetric pair.function setup(el) {}function destroyElement(el) {}
Handler naming
45.4. A function bound as an event listener MUST be named
handle{Target}{Event}, where {Target} is optional and
{Event} is the DOM event it handles. A factory that returns a
bound listener MUST be named make{Target}{Event}Handler. The
on{Action} form MUST NOT be used, for module-level declarations
or for listener bindings declared inside a per-element init.
handle* names the trigger, which is fixed; on* tends to name
the outcome, which drifts as the handler grows. on* also reads
as one of the DOM's own inline-handler properties (el.onclick).
// Correct.function handleClick(e) {}function handleTriggerClick(e) {}function makeGroupClickHandler(group) {return (e) => {/* ... */};}// Wrong.function onClick(e) {}function onOpenClick(e) {}
Instance registry
45.5. Each kind of element a module manages MUST have exactly one
init guard. By default it is a module-level WeakMap, named
registry in a single-element module and {noun}Registry per
kind in a multi-element module; registry.has(el) IS the
idempotence guard
Rule 41.9 requires.
An entry MUST be a record object carrying whatever the element's
teardown needs - the AbortController from 45.7, an observer, a
timer - or the literal true where there is nothing to tear down.
No other value MAY be stored. An entry that is a bare
AbortController, a bare element, or any other loose value reads
as a record everywhere else in the codebase, so entry.ac on it
silently resolves to undefined rather than failing.
A module MUST NOT keep a second WeakMap for per-element state
that belongs on the entry. One map per kind of element, and every
other resource a named field on its entry per 45.8; what MUST NOT
happen is a second guard alongside the map.
WeakSet and dataset.{name}Init MUST NOT be used as the guard.
A WeakSet cannot hold the teardown state, and the dataset form
writes JS-internal bookkeeping into the consumer's DOM, where any
consumer that resets attributes can clobber it.
// Correct.const registry = new WeakMap();function initElement(el) {if (registry.has(el)) return;const ac = new AbortController();el.addEventListener('click', handleClick, { signal: ac.signal });registry.set(el, { ac });}// Wrong - the DOM carries the guard, the WeakMap carries nothing.function initElement(el) {if (el.dataset.fooInit) return;el.dataset.fooInit = 'true';}// Wrong - a bare value, and a second map for state the entry should hold.trapRegistry.set(el, ac);backdropRegistry.set(el, backdrop);
45.6. A data-{name}-init marker attribute MAY be set only when
teardown or observation configuration needs to read it - the
destroySelector passed as _register's fifth argument, which is
a CSS selector, or a MutationObserver attributeFilter, which
is a list of attribute names. Neither can query a WeakMap, so the marker is
load-bearing there rather than duplicated, and it becomes that
module's guard: a module whose only per-element state is "was this
initialized" needs no WeakMap beside it. A module that also has
listeners or observers to release still keeps the map for them.
// Correct - the destroy-side selector cannot query the WeakMap.window.Semetrika._register('sidenav', '[data-sidenav]:not([data-sidenav-init="true"])', init, destroy, '[data-sidenav-init="true"]');
Listener teardown
45.7. Every addEventListener call MUST pass either
{ signal } from an AbortController, or { once: true } for a
listener that removes itself. Listeners bound inside a per-element
init take the controller created in that init and stored on the
registry entry; the matching destroy calls entry.ac.abort().
removeEventListener MUST NOT be used at all - nor may disposer
arrays, returned unwire closures, or stored handler references
stand in for the controller.
One abort tears down every listener the init bound, however many
there are, so a listener added later cannot be forgotten in the
teardown. A listener with a shorter life than its element - a
transitionend guard that stops mattering once the transition
settles - takes its own controller scoped to that span, or once
when it truly fires only one time.
// Correct.function initElement(el) {if (registry.has(el)) return;const ac = new AbortController();el.addEventListener('click', handleClick, { signal: ac.signal });el.addEventListener('keydown', handleKeydown, { signal: ac.signal });registry.set(el, { ac });}function destroyElement(el) {const entry = registry.get(el);if (!entry) return;entry.ac.abort();registry.delete(el);}// Wrong - one stored reference per listener; adding a third listener// and forgetting the matching removal leaks silently.function destroyElement(el) {const entry = registry.get(el);if (!entry) return;el.removeEventListener('click', entry.onClick);el.removeEventListener('keydown', entry.onKeydown);registry.delete(el);}
45.8. Resources an AbortController cannot cancel - observers,
timers, and cleanup callbacks returned by a third-party library -
MUST be stored as named fields on the same registry entry and
torn down explicitly in the matching destroy. A timer handle
discarded at statement level cannot be cleared. A zero-delay
setTimeout that only re-reads state once the current event
settles holds no resource and is the one exemption.
registry.set(el, { ac, observer, timer });function destroyElement(el) {const entry = registry.get(el);if (!entry) return;entry.ac.abort();entry.observer.disconnect();clearTimeout(entry.timer);registry.delete(el);}
Scope collection
45.9. A module MUST collect its elements via
window.Semetrika._collect(root, selector). A module MUST NOT
reimplement the scope walk - _collect already returns matching
descendants plus the scope element itself when it matches, and a
local copy drifts from the orchestrator's behavior.
Missing prerequisites
45.10. A per-element init whose prerequisite is absent - the
element a selector does not find, an attribute a consumer left
empty, a parent the element is not attached to yet - MUST return
WITHOUT claiming the registry, so the next dispatch retries it.
A sentinel entry (true, {}) that claims the element and stops
it being reconsidered MUST NOT be written.
boot.js installs a childList observer precisely so DOM built
later is enhanced. Which prerequisites can appear later is not a
question a module can answer: a consumer may inject a
[role="tablist"] into a live [data-tabs], or fill in an empty
data-avatar-hash, at any point. Claiming and stopping leaves the
element permanently inert with no route back short of an explicit
destroy() then init().
// Correct - the element is reconsidered once the tablist exists.function initElement(container) {if (registry.has(container)) return;const tablist = container.querySelector('[role="tablist"]');if (!tablist) return;/* ... */}// Wrong - the sentinel makes the missing prerequisite permanent.function initElement(container) {if (registry.has(container)) return;const tablist = container.querySelector('[role="tablist"]');if (!tablist) {registry.set(container, {});return;}}
Keyboard navigation
45.11. Arrow-key navigation over a collected list MUST wrap at
both ends, via window.Semetrika._step(items, index, delta).
Clamping at the first and last entry MUST NOT be used, and the
wrap MUST NOT be written as a local modulo expression.
Wrapping is what the WAI-ARIA composite-widget pattern specifies,
and the difference is one a keyboard user feels directly: two
sibling navigation components on one page that disagree about what
ArrowDown does at the last item read as a broken control rather
than as a design choice. Home and End stay absolute.
A scroll region whose looping is a declared hook (data-carousel-loop) clamps at its ends until the hook is set: the consumer chose the boundary, so the wrap is theirs to enable.
Shared runtime helpers
45.12. Where window.Semetrika publishes a helper for a behavior, a
module MUST call it rather than implement its own. The helpers are
_collect (45.9), _step (45.11), _focusables, _hash,
_uniqueId, _numberAttr, _label / _labelText, and
_globals (45.13). A module may not export, so window.Semetrika
is the only surface a second module can reach; a local copy is
invisible to every other module and drifts from the shared one
silently.
Math.random() MUST NOT be used to build an element id.
_uniqueId(base) is deterministic, so a generated id can be
asserted on and produced output stays byte-identical between runs
per Rule 53.15.
// Correct.const id = window.Semetrika._uniqueId('timepicker-hours');const step = window.Semetrika._numberAttr(input, 'data-timepicker-step', { fallback: 30, min: 1 });// Wrong - a local copy of a shared behavior, and a random id.function djb2(str) {/* ... */}const id = `timepicker-hours-${Math.random().toString(36).slice(2, 10)}`;
Document-level lifecycle
45.13. Document- and window-level listeners, and any observer or
timer shared across a module's instances, MUST install with the
module's first claimed element and release with its last, through
window.Semetrika._globals(install, uninstall). Its acquire() and
release() are called from the per-element init and destroy;
ensure() installs without taking a reference, for a module whose
surface answers before any element opts in.
The count tracks what the module owns. A document query counts
what the page contains, and the two diverge in both directions: a
destroy(root) scoped to a subtree leaves matching elements
elsewhere, and an explicit destroyAll() leaves every element in
place while dropping its registry entry.
const globals = window.Semetrika._globals(() => {globalAc = new AbortController();document.addEventListener('keydown', handleDocumentKeydown, { signal: globalAc.signal });},() => {globalAc.abort();globalAc = null;},);function initElement(el) {if (registry.has(el)) return;registry.set(el, { ac });globals.acquire();}function destroyElement(el) {const entry = registry.get(el);if (!entry) return;entry.ac.abort();registry.delete(el);globals.release();}
45.1, 45.2, 45.3, 45.4, 45.5, 45.6, 45.7, 45.12, 45.13, 45.8 by yarn cli 45 (findInvalidModuleWrapper, findInvalidLifecycleNames, findInvalidHandlerNames, findInvalidRegistryShape, findManualListenerTeardown, findNonRecordRegistryEntries, findReimplementedHelpers, findAdHocGlobalLifecycle, findDiscardedTimers in packages/cli/src/rules/45.js). 45.9-45.11 are review only. See enforcement.md.