npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

on_the_money

v0.18.0

Published

Opinionated, attribute-driven, standards-oriented modern framework. Native browser APIs only. See README.md for the authoring context.

Readme

on_the_money.js

This README is the authoring context for AI agents using on_the_money. Read top-to-bottom for a complete picture; everything you need to write an OTM app is here. No satellite docs.

Opinionated, attribute-driven, standards-oriented modern framework for the web. Native browser APIs only. ESNext.

UI signal state — theme, page, modal-open, form-error, the boolean and enum flags that drive visual transitions — lives in DOM attributes; structured data (lists of records, collections, async results) lives in JS like everywhere else. Reactivity is delegated to the platform, not reimplemented: CSS attribute selectors respond to state visually, [data-text] projects state into text, and MutationObserver fans state into imperative calls — the framework adds no reactive machinery of its own. Events use one delegated listener per (parent, type) pair. Routing uses the History API. Localization uses Intl. There is no virtual DOM, no JSX, no transpilation step, no proprietary tooling. The framework is a thin layer of conventions over the platform.

Install

npm install on_the_money

Quickstart

A complete two-file app. index.html carries semantic structure, app.js carries behavior.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title data-i18n="app_title">My App</title>
  <link rel="stylesheet" href="./substrate.css">
  <script type="module" src="./app.js"></script>
</head>
<body>
  <main>
    <h1 data-i18n="app_title">My App</h1>
    <p data-text="greeting">Press the button.</p>
    <button data-action="greet" data-i18n="btn_greet">Greet</button>
  </main>
</body>
</html>
// app.js
import { on, the } from "on_the_money";

await the.boot();

on("main", "click", '[data-action="greet"]', () => {
  the("greeting", "Hello, Alice!");
});

Localizable interface copy uses data-i18n; UI state mirrors use data-text, with source-language fallback text when practical. Ordinary document content needs neither marker nor attribute mirror (see Literal document content). This source-only document needs no translation endpoint or dictionary files, including for visitors requesting another language: the rendered English remains available. On boot, keys opted in via persistKeys replay from localStorage onto body data-* and [data-text] mirrors; by default nothing persists.

The substrate stylesheet

The lint stack bans class selectors, so an OTM site rides on a classless substrate — a stylesheet satisfying four contract clauses:

  1. Styles semantic HTML directly — zero classes required (<main>, <nav>, <article>, <form>, <button>, <input> with <label>).
  2. Responds to ARIA state attributes ([aria-invalid], [aria-busy], [disabled], <dialog open>).
  3. Exposes its design tokens as CSS custom properties (--otm-*), so style.css themes by variable override.
  4. Hooks theme switching on a data attribute ([data-theme="dark"] / [data-theme="light"]), so the("theme", ...) switches it.

on_the_money ships a distilled, zero-class, modern-CSS foundation derived from Pico Classless (MIT) plus all 20 Pico color schemes as CSS subpath exports (0 bytes to the JS core bundle):

/* Default: classless schema + azure scheme */
@import "on_the_money/css";

/* Or pick any of the 20 Pico schemes explicitly */
@import "on_the_money/css/schema";
@import "on_the_money/css/schemes/jade";

Available schemes: amber, azure, blue, cyan, fuchsia, green, grey, indigo, jade, lime, orange, pink, pumpkin, purple, red, sand, slate, violet, yellow, zinc. Any other contract-satisfying classless stylesheet remains swappable.

Semantic button hierarchy & action tokens. schema.css honors native HTML button types directly — zero custom presentational attributes (data-tone, data-size, etc. do not belong in HTML):

  • <button>, <button type="submit">, <input type="submit">, [role="button"] → primary (--otm-primary-background / --otm-primary-inverse).
  • <button type="button">, <input type="button"> → secondary (neutral fill --otm-secondary-background / --otm-secondary-border / --otm-secondary), preventing primary-fill fatigue in toolbars, cards, and modal controls.
  • <button type="reset">, <input type="reset"> → quiet / outlined (transparent fill, subtle border).
  • For domain-specific destructive actions (button[data-action^="delete-"], button[value="remove"]) and custom button tiers, schema.css exports derived light/dark-safe tokens (--otm-secondary, --otm-secondary-background, --otm-secondary-border, --otm-secondary-hover-background, --otm-secondary-hover-border, --otm-secondary-focus, and --otm-danger, --otm-danger-inverse, --otm-danger-background, --otm-danger-hover-background, --otm-danger-border, --otm-danger-focus). Compact row sizing belongs in contextual structure.css selectors (td button, li > button), not HTML modifier attributes.
  • Form action bars (form > footer): renders as a wrapping flex row aligned to the inline end (justify-content: flex-end, align-items: center, gap: calc(var(--otm-spacing) * 0.5), margin-block-start: var(--otm-spacing)), staying inside card measure without inheriting article > footer's negative inline bleed. Override per form in @layer structure (e.g. justify-content: flex-start for long single-column forms). For top-level <dialog> elements placed outside <main>, wrap dialog contents in <article> (styled via dialog:has(> article)) so <footer> does not expose a duplicate contentinfo landmark under HTML-AAM.

CSS architecture (the 5-S stack)

Both this framework's conventions and its dictatorial Stylelint rules enforce a five-layer CSS cascade, ordered explicitly via native @layer:

@layer schema, scheme, structure, style, state;
on_the_money/css/
├── schema.css          # @layer schema    — classless semantic HTML + ARIA foundation
└── schemes/<name>.css  # @layer scheme    — Pico color palette tokens (light & dark)

styles/ (app-authored)
├── structure.css       # @layer structure — layout scaffolding only: grid, flex, gap, landmarks
├── style.css           # @layer style     — brand skin only: --otm-* overrides, fonts, surfaces
└── state.css           # @layer state     — the ONLY OTM-aware layer: [data-*] / [aria-*] rules

Because cascade precedence follows @layer schema, scheme, structure, style, state;, there are zero specificity wars and zero !important hacks: state.css always beats style.css and structure.css. Each 5-S file wraps its rules in its own @layer <name> { ... } block (unlayered CSS beats every @layer in browsers). otm/layer-discipline enforces those @layer wrappers, rejects layout rules and DOM state selectors in style.css (while keeping ephemeral interaction pseudos like :hover and :focus-visible in style.css), rejects skin/state rules in structure.css, and rejects unconditional baseline rules in state.css. Keeping state.css isolated keeps the state vocabulary greppable and auditable by otm-lint (HTML-106/107) and the deletion test.

Exports

import { on, the, _t, route, $, $$ } from "on_the_money";

Aliases on the: the.t === _t, the.route === route, the.form(formEl), the.flat(obj, sep?), the.match(pattern, path?), the.boot(options?). On on: on.emit(el, event, detail?), on.target(target, event, fn, options?). On route: route.go(path, options?). Live accessors on the: the.dictionary, the.locale.

For tests: import { setupDOM } from "on_the_money/test" (see Testing your app).

API

on(parent, event, selector, fn) — event delegation

| Arg | Type | Notes | | --- | --- | --- | | parent | Element \| string \| null | If string, resolved via document.querySelector. If falsy, defaults to document.body. | | event | string | Any DOM event name ("click", "submit", "mounted", etc.). | | selector | string | CSS selector matched via event.target.closest(selector). | | fn | (event, target) => void | target is the element the selector matched. |

Returns an () => void unsubscribe function. All four arguments are required; for a form's own submission, use on(form, "submit", "form", handler). A missing selector or handler fails at registration, and otm/prefer-on diagnoses incomplete calls.

const off = on("#list", "click", "[data-action='delete']", (e, target) => {
  target.closest("[data-item]").remove();
});
off(); // detaches the listener

on.emit(el, event, detail) — CustomEvent dispatch

Dispatches a bubbling, cancelable CustomEvent on el. el may be an element or a selector string.

on.emit("#cart", "items-changed", { count: 3 });

on.target(target, event, fn, options?) — shared non-Element EventTargets

Subscribes to a non-Element EventTarget (window, document lifecycle events, visualViewport, AbortSignal, MediaQueryList) without overwriting sibling modules' handlers. Throws a TypeError if target is a DOM Element — DOM elements always use delegated on(parent, event, selector, fn). Accepts { signal, once, passive, capture } and returns an () => void unsubscribe function (also detaching automatically when signal aborts, or no-opping when signal.aborted is already true).

const stopResize = on.target(window, "resize", () => syncViewport(), {
  signal: page.signal,
});
stopResize();

the(...) — state

Polymorphic on a single disambiguator: args[0] instanceof Element. Three call shapes per scope (get, set, batch).

| Call | Behavior | Returns | | --- | --- | --- | | the(key) | Read body data-KEY. | string \| null | | the(key, val) | Write body attribute + [data-text="key"] mirrors document-wide. Persists to localStorage only if key is in persistKeys. | document.body | | the(key, null) | Delete: remove the attribute, clear [data-text] mirrors, remove the persisted entry. | document.body | | the({ k: v, ... }) | Batch global write; null values delete. | document.body | | the(el, key) | Read scoped attribute on el (or aria-mapped equivalent). | string \| null | | the(el, key, val) | Write scoped attribute on el + descendant [data-text="key"]. | el | | the(el, key, null) | Delete the scoped attribute, clear descendant mirrors. | el | | the(el, { k: v, ... }) | Batch scoped write; null values delete. | el |

  • Key naming. State keys MUST be canonical lowercase kebab-case (^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$) — e.g. "theme", "model-offline", "post-url". There is no silent camelCase or snake_case conversion: one literal spelling holds across HTML (data-model-offline, data-text="model-offline"), CSS ([data-model-offline]), JS (the("model-offline", "1"), the({ "model-offline": "1" })), and localStorage. Non-kebab keys throw a TypeError at runtime and fail otm/kebab-state-keys in ESLint.

  • Projection is idempotent per target. Every write visits its live bindings in one combined [data-text],[data-bind] scan, changing text or an attribute only when that target's current value differs from the normalized output. Equal [data-text] content retains its existing nodes and native selection; new or externally changed bindings still hydrate even when the owner's state is unchanged. Empty strings remain distinct from null deletion. Opted-in storage writes and their errors are unaffected. For high-frequency regions (streaming status bars, timers, counters on large transcripts), prefer scoped the(containerEl, "status", val) so DOM lookup stays $O(1)$ within that container rather than walking the full document.

  • Persistence is opt-in. Default behavior writes attributes only — nothing persists to localStorage. Declare the.boot({ persistKeys: ["theme", "lang"] }) to opt specific keys in. The boot replay loads only those keys back. Common persistKeys for an i18n + theme app: ["theme", "lang"].

  • Deletion is null. the(key, null) removes the attribute, clears every [data-text="key"] mirror to empty, and removes the persisted localStorage entry if the key is in persistKeys. undefined still throws — a missing value is a bug, an explicit null is a delete.

  • ARIA mapping is element-scoped only (closed 4-key set, key → attribute): expanded, selected, checked, disabled → aria-* when writing via the(el, ...). Criterion: HTML5 widget/form boolean states only. hidden is deliberately not mapped — aria-hidden="true" hides from screen readers without visually hiding the element, so the(el, "hidden", true) writes data-hidden="true" just like global the("hidden", true). Use native [hidden] (or CSS [data-hidden="true"] { display: none; }) to hide visually, and el.setAttribute("aria-hidden", "true") explicitly for decorative icons. Other ARIA attributes (aria-invalid, aria-controls, etc.) also use el.setAttribute(...).

  • Dynamic <title> and other <head> slots: global the(key, val) writes walk the entire document for [data-text="key"] matches, not just body. Put <title data-text="page-title">Default</title> in <head> and the("page-title", "X") updates it.

  • Global and scoped keys share one [data-text] namespace. A global write updates every matching slot in the document — including slots inside cloned components and [data-otm-scope] subtrees. Never reuse a global key as a scoped slot key inside a <template> or [data-otm-scope]; otm-lint flags both as HTML-104.

  • Nested scope boundaries (data-otm-scope). Scoped writes (the(el, ...)) stop at any nested descendant carrying data-otm-scope (including self-scoped child roots such as <a data-otm-scope data-text="name">), so composing nested cards or nested $.reconcile() lists never clobbers child slots that share key names (name, url, status) with their parent. Works uniformly across SSR markup, $.clone(), $.cloneEach(), and $.reconcile().

    <article id="workspace-card" data-otm-scope>
      <a data-text="name" data-bind="href:url">Workspace</a>
      <section id="session-card" data-otm-scope>
        <a data-text="name" data-bind="href:url">Session</a>
      </section>
    </article>
    the($("#session-card"), { name: "Session A", url: "/sessions/a" });
    the($("#workspace-card"), { name: "Core", url: "/workspaces/core" });
    // #session-card's name/url slots stay untouched.
  • Attribute projection: data-bind="attr:key". The attribute-space sibling of [data-text] — state projects into plain attributes (href, src, datetime, value, title) declaratively. Space-separate multiple bindings; keys are kebab-case like every slot key; the(el, { key: null }) removes the bound attribute.

    <template id="profile-card">
      <article data-item>
        <a data-text="name" data-bind="href:profile-url">@someone</a>
        <time data-text="joined" data-bind="datetime:joined-at">recently</time>
      </article>
    </template>
    const card = $.clone("#cards", "#profile-card");
    the(card, { name: "@alice", "profile-url": "/@alice", joined: "May 2026", "joined-at": "2026-05-01" });
  • Truly one-off attributes still use el.setAttribute(name, val) directly, colocated with the write (Discipline #2). data-bind is for attributes that carry per-element state-derived data (every card's link); setAttribute is for structural one-offs. If you're writing the same setAttribute line in every clone loop, that's a data-bind.

  • Booleans coerce to "true"/"false" inside the setter. the(el, "checked", true) writes "true".

  • Values MUST be strings, finite numbers, booleans, or null. Numbers and booleans stringify; null deletes. Objects, arrays, functions, symbols, bigint, NaN, and infinities throw at runtime. Pass nested objects through the.flat(...) first.

  • the(key, undefined) throws. Two args means set; missing val is a contract violation.

the.form(formEl) — form extraction

Walks input, select, textarea descendants. Skips unnamed, disabled, submit/button/reset controls, file inputs, and unchecked checkboxes/radios. Parses bracket-notation names into a nested object. Unsafe path segments (__proto__, prototype, constructor) throw instead of entering the result graph:

the.form(form);
// <input name="user[name]" value="Alice">     → { user: { name: "Alice" } }
// <input name="tags[]" value="a">             → { tags: ["a"] } — [] names are
//                                               arrays at every cardinality
// <select name="colors[]" multiple>            → every selected option's value

Returns a nested object (matches browser submission semantics). Compose with the.flat before feeding to the(el, {...}).

the.flat(obj, sep = "-") — nested-to-flat

the.flat({ user: { name: "Alice" }, tags: ["a", "b"] });
// → { "user-name": "Alice", "tags-0": "a", "tags-1": "b" }

the.flat({ a: { b: 1 } }, ".");
// → { "a.b": 1 }

Throws on non-object input.

the.boot(options?) — explicit init

Importing the module does nothing. Call the.boot() at the consumer's entry point.

await the.boot({ signal, locales, dictionary, namespace, locale, defaultLocale, persistKeys });

| Option | Type | Behavior | | --- | --- | --- | | signal | AbortSignal | Aborts the i18n fetch. | | locales | string | Override the <meta name="i18n" content> path. | | dictionary | object | Inline dictionary used for DOM and programmatic translation, including in the source language. Skips fetching. | | namespace | string | Sets localStorage prefix to ${namespace}: (default otm:). Must be set before any state ops. | | locale | string | Requested locale. Takes precedence over query, stored, document, and browser values; boot resolves it against available translations and the source document. | | defaultLocale | string | Actual source language of the rendered HTML. Defaults to <html lang>; an explicit value also sets that document language. Source text is the terminal fallback; no source dictionary is required. | | persistKeys | string[] | Global state keys that should persist to localStorage. Default: empty — nothing persists. Writes still update the body attribute and any [data-text] mirrors regardless. Boot replay rehydrates only these keys. Use for stable preferences: ["theme", "lang"]. Scoped state (the(el, ...)) never persists regardless. |

Boot sequence:

  1. Select the requested locale: explicit locale → ?lang= → opted-in localStorage["${prefix}lang"] → <html lang> → navigator.language → "en". The server's document language outranks the browser's passive preference. To deliberately select the browser's preference, pass locale: navigator.language and keep <html lang> set to the actual source language.
  2. Load an inline dictionary if provided, without fetching. An explicitly supplied dictionary is used for both DOM and programmatic translation, including in the source language.
  3. Otherwise, when an endpoint is declared, load the available dictionaries in the requested locale's lookup chain, followed by data-fallback (default: the declared source language, or "en" when undeclared). Lookup uses canonical Unicode locale tags and progressively removes variant/region subtags, retaining script compatibility: fr-CA → fr, sr-Latn-RS → sr-Latn. At the source language, load its dictionary only if explicitly listed in data-available, then terminate the chain. Otherwise use source text without fetching a source file. A same-language regional dictionary can still override the source when it is a closer match. With no data-available manifest, only a non-source fallback file is fetched; list available files to enable regional lookup.
  4. A network, HTTP, JSON, or dictionary-shape failure warns with its original cause and continues through the chain to source text. Aborting rejects boot. Invalid inline dictionaries and locale identifiers reject as authoring errors.
  5. Set the.locale to the effective primary locale. Preserve the requested regional settings when compatible with that language and script (fr-CA can use fr.json); otherwise use the fallback locale. The requested URL/storage preference is not rewritten.
  6. Replay opted-in storage keys (except lang), then translate [data-i18n] in the document, including the head. Resolve each message through the loaded dictionaries; a miss preserves its original source text. Subsequent boot or _t() calls restore that original text on a miss, rather than retaining a previous translation.

English is the convention used by examples and unspecified defaults, not an enforced source language. Declare another source using <html lang="de"> or defaultLocale: "de"; OTM does not require an English dictionary. Declaring the source language prevents a guessed source-file fetch. An explicitly advertised source catalog remains useful for dynamic messages; without a source declaration, boot cannot distinguish it from other dictionaries.

This is a documented lookup profile, not full CLDR best-fit matching or transliteration. Native Intl.Locale handles canonicalization and likely scripts; OTM does not bundle linguistic tables. Use hyphenated tags (fr-CA, not fr_CA). Dictionary filenames retain the spelling in data-available, while matching is canonical.

Storage access is opt-in for both reads and writes. With no persisted keys configured (or after persistKeys: [] clears them), boot and state operations never access localStorage. Boot reads only opted-in keys; it does not enumerate unrelated storage. When persistence is explicitly enabled, browser storage failures propagate as their original errors from the operation, including boot, writes, and deletion. A failed persisted write may already have updated the DOM; it must not be treated as a successful save.

Writing data-i18n elements: always include the source-language text inside as a fallback:

<!-- good — SEO fallback, no-JS fallback, no-flash default -->
<h1 data-i18n="title">Welcome to the app</h1>

<!-- avoid — page is blank until hydration -->
<h1 data-i18n="title"></h1>

Partial translations are supported. Missing messages retain the source text already in the document; no duplicate source-language JSON is needed. Translated carriers get lang for the supplying dictionary; source fallback retains its original language attributes. The document's lang continues to describe the source, so untranslated passages inherit it correctly. Keep carriers' source text in place before their first translation; OTM retains it per element for subsequent language changes, not as a second template graph.

Static fallback text is not an interpolation template: 0 comments cannot describe a later count of one or two. For changing plural/interpolated messages, provide a real source-language catalog and advertise it in data-available (or supply an inline dictionary). That catalog may contain only the dynamic messages; duplicating all static source text is unnecessary. The same per-message cascade uses it after partial translations. Source-only pages without dynamic messages still need no endpoint or catalog.

Language and direction are separate HTML concerns. Authors supply dir="rtl" for right-to-left documents or passages, and dir="auto"/bdi for appropriate dynamic text. OTM does not infer layout direction from lang. See W3C directionality guidance.

_t(key, options) — Intl localization

_t("hello");                                       // string lookup in the.dictionary
_t("hello", { name: "Alice" });                    // {name} → "Alice"
_t("items", { qty: 5 });                           // Intl.PluralRules picks { one, other } entry
_t("price", { val: 9.99, type: "currency", currency: "EUR" });  // Intl.NumberFormat
_t("when", { val: Date.now(), type: "date" });     // Intl.DateTimeFormat

_t(node);                                          // hydrate every [data-i18n] inside node
_t();                                              // hydrate the document, including the head

Missing dictionary keys preserve original source textContent during element hydration; the programmatic string form searches the same dictionary chain, then returns the key (it does not search the DOM for a template). Interpolation replaces every occurrence of a {token}, and $-characters in values are inert. When options.type is "currency" or "date", Intl formatting of options.val runs regardless of whether the dictionary has an entry — useful in default-locale apps that skip the fetch.

DOM translation follows the same per-target projection contract as the(): unchanged final text preserves existing nodes and native selection, including during source restoration. Language attributes update independently when the supplying language changes, even if the text stays identical; unchanged language attributes are not rewritten.

Dictionaries map keys to strings (including intentional empty strings) or plural objects with string values under zero, one, two, few, many, and other; other is required. Plural selection uses the supplying dictionary's locale. Number/date interpolation retains compatible regional preferences, but does not apply another language's formatting to a fallback message. the.dictionary exposes the primary dictionary; assigning it replaces the whole chain and associates that inline dictionary with the.locale. Use _t() for lookup through fallbacks.

Plural categories are grammatical categories, not exact quantities: French one includes zero, so write "{qty} commentaire", not "1 commentaire". Attribute values are strings; use ISO date text in data-i18n-val, not a stringified millisecond timestamp. Supply the value before activating data-i18n-type="date"; empty or invalid active date values are lint errors (HTML-027), and invalid dates still fail at runtime.

Formatting vocabulary is Intl's, verbatim. Directive attributes mirror Intl option names one-to-one — data-i18n-currency → currency — and OTM defaults none of them: type: "currency" without an explicit currency throws (the platform itself refuses to infer currency from locale, and it validates ISO 4217 codes with a RangeError). The framework ships Intl plumbing, never a currency choice; HTML-025 catches the missing declarative code at lint time.

[data-i18n] element binding (always include source-language fallback text inside):

<span data-i18n="cart_items" data-i18n-qty="3">3 items</span>
<span data-i18n="price" data-i18n-val="9.99" data-i18n-type="currency" data-i18n-currency="USD">$9.99</span>

route(callback, options?) — pushState router

const off = route((pathname, search, hash) => {
  // render whatever fits this route
});

Fires the callback on initial mount (unless { initial: false } is passed for server-rendered documents that are already hydrated), on popstate, on hashchange (deduplicated after popstate so fragment navigation fires once), and on intercepted internal <a> clicks. Left to the browser: modified clicks (meta/ctrl/shift/alt, non-primary button), [download] links, data-external, target="_blank", and cross-origin hrefs. Clicking a link to the current URL is a no-op. Hash-only same-page links are left to the browser and invoke the callback once.

Returns an unsubscribe function. One router at a time: calling route() while another registration is active throws — unsubscribe the first.

Selective enhancement: route(cb, { match: "[data-route]", initial: false }) intercepts only links matching the selector while leaving the server-rendered initial document and non-matching links untouched. popstate and route.go behave identically in both modes, so the back button stays correct without any hand-rolled listener.

route.go(path, options?) — programmatic navigation

on("#login-form", "submit", "form", async (e) => {
  e.preventDefault();
  await submitLogin(the.form(e.target));
  route.go("/dashboard", { replace: true });
});

pushState (or replaceState when { replace: true }) + callback invocation in one call. pushState and replaceState never fire popstate, so this is the sanctioned path for redirects (post-submit, auth bounce, canonical URL settlement). Throws if no router is active. Navigating to the current URL is a no-op.

the.match(pattern, path?) — pattern matching with named segments

Express-style colon syntax. Extracts named segments from path (defaults to window.location.pathname). Decodes URI-encoded segments. Returns {name: value} on match, null on no match.

the.match("/@:user/:work/:chapter", "/@alice/great-work/chapter-1");
// → { user: "alice", work: "great-work", chapter: "chapter-1" }

the.match("/about", "/about");
// → {} (matched, no params)

the.match("/:slug", "/about/extra");
// → null (segment count doesn't match)

Scope: :name segments only. No optional segments, regex constraints, wildcards, or nested patterns. If your routing needs those, bring path-to-regexp or similar — the.match is the 80%-case helper, not a router framework.

$(context, selector) / $$(context, selector) — context-aware DOM query

$(el, ".child");        // first match (Element | null)
$$(el, ".child");       // all matches (Array)
$(".child");            // shorthand: context = document
$$(".child");

$.clone(parent, selector, options?) — template instantiation

const el = $.clone("#list", "#tmp");
const head = $.clone("#list", "#tmp", { position: "afterbegin" });   // prepend
const sib  = $.clone(anchorEl, "#tmp", { position: "beforebegin" }); // insert before anchor

Clones the first element of <template selector>, runs _t(el) for i18n hydration, inserts at position (default beforeend — append inside parent), dispatches a bubbling mounted CustomEvent (detail: { parent }) after insertion so the element is at its final position when the event fires. Returns the mounted element. Throws if parent/template is missing.

position values mirror insertAdjacentElement:

| Position | Where | | --- | --- | | beforeend (default) | Inside parent, after its last child. | | afterbegin | Inside parent, before its first child. | | beforebegin | As parent's previous sibling. | | afterend | As parent's next sibling. |

For beforebegin and afterend, the first argument is a sibling reference, not a true parent.

$.cloneEach(parent, selector, items, fill?) — replace-children list rendering

$.cloneEach("#posts", "#post-card", posts, (el, post) => {
  the(el, { title: post.title, permalink: `/posts/${post.slug}` });
});

Clears parent (replaceChildren), clones the template once per item, calls fill(el, item, index), returns the mounted elements. Best for coarse-grained or static renders. Append flows (infinite scroll) stay a manual $.clone loop.

$.reconcile(parent, selector, items, { key, fill?, attr? }) — keyed, focus-preserving list reconciliation

$.reconcile("#turns", "#turn-card", turns, {
  key: (turn) => turn.id,
  fill: (el, turn) => the(el, { title: turn.title }),
});

Imperative, stateless sibling to $.cloneEach for live or interactive lists (streaming feeds, tabs, cards with <textarea> drafts or <details open>). Stores each item's key in a DOM attribute (attr, default data-otm-key) — zero shadow trees or reactive array proxies — reuses existing matching nodes, reorders via native Element.prototype.moveBefore (falling back to insertBefore) so focus, selection, and control state survive updates, clones only missing keys via $.clone, removes stale children, and throws atomically on duplicate or empty keys. Composes directly with the(el, ...)'s idempotent projection. NOT in scope: reactive array proxies, virtual DOM, or nested subtree diffing.

Batteries

The subpaths below are OTM's batteries — the platform's gaps, pre-disciplined. Admission is constitutional; a battery ships only when it clears all five clauses:

  1. It wraps a platform absence (the WebSocket lifecycle: yes; fetch itself: never).
  2. Its contract is an existing web standard or a published machine-readable convention — no code-only inventions.
  3. It lands with its lint rules and doctest coverage on day one.
  4. It lives in a subpath the core bundle never pays for.
  5. It carries an explicit NOT-list.

on_the_money/live — WebSocket battery

The platform gives WebSocket almost nothing: no reconnection, no backoff, no dispatch, no correlation. live() owns exactly that absence and hands your handler the messages — how the data is handled stays the Discipline's job.

import { live } from "on_the_money/live";

const ch = live("/ws", {
  onMessage(type, data, at) {
    if (type === "status") the("model-offline", data.offline ? "1" : "");
  },
  onDown() { the({ "model-offline": "1", rates: "" }); },  // fail closed
  onUp()   { /* colocated recovery, if any */ },
  signal: controller.signal,                            // teardown
});

ch.send({ type: "ping" });
const reply = await ch.request({ type: "filter", q: "cats" }, { takeLatest: true });

| Option | Behavior | | --- | --- | | onMessage(type, data, at) | Every non-reply frame. Unknown types must be ignorable — the vocabulary is append-only. | | onError(error, raw) | Malformed JSON frame. Without this callback, live() warns; either way the connection remains open. | | onDown() / onUp() | Link state hooks. Fail closed in onDown: a dead socket should surface the degraded truth. | | signal | AbortSignal; abort closes the socket and stops reconnecting. |

  • Channel forms. live("/ws", opts) derives ws(s):// from the page origin; full URLs pass through. live({ fromState: "live-channel" }, opts) reads the server-advertised channel from body state and returns null when the page has no live representation — the conditional-mount pattern.
  • Lifecycle owned: jittered exponential backoff (capped 30 s) that resets only after the link holds stable, guarded dial (a throwing constructor reschedules, never orphans the loop), close(1000) is deliberate and terminal.
  • send(frame) is fire-and-forget, dropped while down — best-effort posture.
  • request(frame, { timeoutMs, takeLatest }) stamps a client-monotonic req_id, resolves the echoed reply, and resolves null on down, timeout, or supersession — it never rejects. takeLatest makes it a latest-wins lane: stale replies drop, and while disconnected only the newest frame is held for the next open.
  • Wire contract: server→client frames are { type, at, data } with { type: "hello" } first; the conventions live in examples/live/asyncapi.yaml with a reference server beside it — the contract is what agents build servers against.
  • NOT in scope: auth handshakes, heartbeats, binary frames, offline queueing, presence.

sse(path, options) — Server-Sent Events

Uses native EventSource when headers is omitted, and switches transparently to WHATWG fetch-streaming SSE when headers (a HeadersInit value or (signal) => HeadersInit | Promise<HeadersInit> credential supplier) is provided — giving Bearer-authenticated streams the exact same { types, onMessage, onError, onDown, onUp, signal } and .close() contract as public/cookie streams.

import { sse } from "on_the_money/live";

const outlet = $("#answer");
let answer = "";
const stream = sse("/stream/answer", {
  types: ["token", "done"],
  headers: (signal) => accessHeaders(signal), // omit for cookie/public EventSource
  onMessage(type, chunk) {
    if (type === "done") return the("answering", null);
    answer += chunk;
    if (outlet.textContent !== answer) outlet.textContent = answer;
  },
  onDown() { the("answering", null); },
  signal: controller.signal,
});

Streaming document content: accumulate in JS and insert literal text into an existing display outlet such as <pre id="answer"></pre>, without mirroring the body in attributes. UI flags such as answering still use the(). The equality guard avoids replacing unchanged text; it does not deduplicate appended chunks. In headers mode, sse() forwards Last-Event-ID, honors server retry: hints (falling back to jittered backoffDelay), wakes immediately on online / visible visibilitychange, and treats 204, non-text/event-stream 200, and deterministic 4xx responses (other than 408/429) as terminal rather than retrying. Pin scroll with CSS overflow-anchor; typing-effect motion belongs in CSS behind prefers-reduced-motion. NOT in scope: correlation (SSE is one-way — request/reply is live()'s job).

on_the_money/clipboard — copy affordances

Clipboard writes are behavior CSS cannot express, and the API exists only in secure contexts. This battery is the capability-declaration pattern in 20 lines: render copy buttons hidden, declare the capability as state, let state-CSS reveal them. With JS off or no clipboard API, the buttons never appear — no dead controls.

<button data-copy="npm install on_the_money" data-i18n="copy-cmd">Copy</button>
[data-copy] { display: none; }
body[data-clipboard="available"] [data-copy] { display: inline-block; }
[data-copy][data-copied="true"] { outline: 2px solid var(--ok, green); }
import { clipboard } from "on_the_money/clipboard";

const off = clipboard();   // null when the capability is absent

Clicking any [data-copy] writes the attribute's value to the clipboard and pulses data-copied="true" on the button for two seconds ({ resetMs } to tune) — the confirmation flash is CSS's job. Capability declaration generalizes: feature-detect once, write one state attribute, and every dependent control is revealed by stylesheet rule instead of JS existence checks scattered per control.

on_the_money/combobox — WAI-ARIA APG combobox

Native <datalist> cannot separate option IDs from labels, render multi-field options, or support predictable async filtering across browsers. on_the_money/combobox is a zero-core-cost subpath battery that implements the W3C WAI-ARIA APG Combobox Pattern directly over semantic DOM elements ([role="combobox"], [role="listbox"], [role="option"]).

<label for="model-input">Model</label>
<input
  id="model-input"
  type="text"
  role="combobox"
  aria-controls="model-listbox"
  aria-expanded="false"
  aria-autocomplete="list"
  autocomplete="off"
>
<ul id="model-listbox" role="listbox" aria-label="Models" popover="manual">
  <li role="option" data-value="claude">Claude</li>
  <li role="option" data-value="gemini">Gemini</li>
</ul>
@layer state {
  [role="option"][data-active="true"] {
    background-color: var(--otm-primary-focus);
  }
  [role="option"][aria-selected="true"] {
    font-weight: 700;
  }
}
import { $$, on } from "on_the_money";
import { combobox } from "on_the_money/combobox";

const ac = new AbortController();
const combo = combobox("#model-input", {
  signal: ac.signal,
  onSelect(option, input) {
    input.value = option.textContent.trim();
  },
});

on("#model-input", "input", '[role="combobox"]', (_e, input) => {
  const q = input.value.trim().toLowerCase();
  for (const opt of $$("#model-listbox [role='option']")) {
    opt.hidden = Boolean(q) && !opt.textContent.toLowerCase().includes(q);
  }
  combo.sync();
});

What combobox(target, options?) owns:

  • ARIA wiring & reflection: resolves the controlled [role="listbox"] from aria-controls (failing fast if missing), manages aria-expanded, assigns stable IDs to options lacking one, tracks aria-activedescendant + data-active="true" (CSS highlight hook) while keeping DOM focus on the combobox, and updates aria-selected="true" on selection.
  • WAI-ARIA APG keyboard interaction: ArrowDown, ArrowUp, Alt+ArrowDown/Alt+ArrowUp, Enter, Escape (closes when open; clears editable <input> and fires "input" when closed unless clearOnEscape: false), and Tab (closes without trapping focus). Skips [hidden] options, [hidden] parent groups, and [aria-disabled="true"], ignores IME composition (e.isComposing), preserves native Home/End/ArrowLeft/ArrowRight caret movement in editable <input> comboboxes, and supports Home/End/Space on select-only [role="combobox"] buttons.
  • Pointer & Top Layer: preserves combobox focus on listbox mousedown, selects on option click, dismisses on outside click or blur, toggles [hidden] on standard listboxes, or calls native showPopover()/hidePopover() when the listbox carries popover="manual".
  • External DOM composition: call combo.sync() after filtering via [hidden] or updating options with $.reconcile() / $.cloneEach() to assign missing option IDs and clear stale aria-activedescendant. otm-lint (HTML-030) statically validates combobox markup wiring.

Options: { onSelect?, onOpen?, onClose?, wrap = true, openOnFocus = true, clearOnEscape = true, closeOnSelect = true, signal? }. Returns { input, listbox, expanded, activeOption, open(), close(), sync(), select(option), dispose() }.

NOT in scope: network fetching or caching, query debouncing, client-side filter engines, option/template rendering (compose with SSR, $.cloneEach(), or $.reconcile()), custom JS positioning engines (use CSS / [popover="manual"] / CSS Anchor Positioning), virtual scrolling, or multi-select tag pills.

The Discipline

on_the_money adds no reactivity primitives of its own. No signal, effect, autorun, watch, atom, store, derived state, or subscription. There is also no event broadcast on the() writes. Reactivity is delegated to the platform — CSS selectors, [data-text] projection, MutationObserver — not absent, and not yours to reimplement. If you find yourself reaching for a reactive primitive — including importing one from another library — you're solving a problem the framework rejects.

Instead, the framework has three state-response mechanisms, each with one job:

1. CSS attribute selectors handle state → visual

Default. Anything visual goes through [data-key="value"] selectors in your stylesheet.

body[data-modal="session-expired"] #session-expired-modal { display: block }
body[data-page="home"] main > section[data-route="home"] { display: block }
[data-state="loading"] progress { display: inline }
the("modal", "session-expired");   // CSS rule above runs the visual change

No JS step between the the() write and the visual update. The CSS rule is the correspondence. This is the framework's reason for existing — DOM-as-state-database is valuable specifically because CSS can read that database without JS.

2. Imperative API calls colocated with state writes

For one-off platform side effects (dialog.showModal(), el.focus(), el.scrollIntoView(), media .play(), animation triggers), the imperative call lives in the same on() handler that wrote the state.

on(document.body, "click", '[data-action="open-modal"]', () => {
  the("modal", "session-expired");
  $("#session-expired-modal").showModal();
});

Cause (user click) and imperative effect (showModal()) are colocated. The the() write records the state; the platform call performs the imperative action. No subscriber between them.

3. MutationObserver for DRY of imperative responses across many call sites

When the same state can be written from multiple places (user click, fetch handler, boot replay, postMessage) and they all need the same imperative response, observe the attribute once:

new MutationObserver(() => {
  const want = the("modal") ?? "";
  for (const open of $$("dialog[open]")) {
    if (open.id !== `${want}-modal`) open.close();
  }
  if (want) $(`#${want}-modal`)?.showModal();
}).observe(document.body, { attributes: true, attributeFilter: ["data-modal"] });

The observer doesn't enable reactivity — it deduplicates the imperative response. Any place in the codebase that changes data-modal gets the same dispatch logic without copy-pasting. OTM state attributes, scoped ARIA attributes, data-bind targets, and localization lang attributes are not rewritten when their values already match: these no-ops produce neither mutation records nor custom-element attribute callbacks. State records a value; it is not a repeatable command channel. For an action that must run again without a state change, call the imperative API or dispatch an explicit event with on.emit.

When MutationObserver is right vs wrong

| Right (the platform call does work CSS can't reach) | Wrong (CSS's job) | | --- | --- | | el.focus(), el.blur() — moving keyboard focus | Showing/hiding via display: none | | el.scrollIntoView(), window.scrollTo(...) — viewport movement | Changing color, layout, transform | | media.play(), media.pause() — playback state | Adding/removing a class | | el.animate(...) — Web Animations timing | Conditional opacity / visibility | | el.requestFullscreen() — browser mode | Animation triggers expressible as CSS transitions | | navigator.clipboard.writeText(...) — out-of-DOM side effects | Reimplementing attribute-to-text state bindings (use [data-text]) |

dialog.showModal() is a borderline case: it shows the dialog (visual) AND traps focus, paints the backdrop, registers an Escape handler, and announces modal semantics to assistive tech (behavioral + a11y). If you want only the visual, dialog[open] + CSS suffices. If you want the bundled behavior, call showModal() — and reach for MutationObserver only if data-modal can be set from multiple call sites that all need the same dispatch.

Do not use a MutationObserver to reimplement CSS styling or [data-text] state bindings. Those already own their respective state responses. Inserting document content received from a fetch or stream is a separate application operation, not an attribute-to-text binding; native DOM insertion is appropriate there.

The deletion test

The single best self-check: strip every JS function except on() handlers, the imperative calls inside them, and any MutationObserver that handles a many-sites imperative response. Open the page; mutate body data-* attributes in DevTools.

  • Does the page respond correctly? You're idiomatic.
  • Does it not? You're missing either a CSS rule (most likely) or an imperative call at a state-write site (occasionally).

The enhancement ladder

Classify every JS module by why a page refresh cannot replace it — the rung justifies the module's existence:

  1. Initial structure and content — the server renders a real document. Browser enhancement does not replace that baseline.
  2. State → visual — CSS's job (mechanism #1). No JS beyond the the() write.
  3. Server-initiated updates — a refresh cannot know to happen (a payment confirmed, a comment arrived). live()/sse() intake can update UI state or insert document content into existing outlets.
  4. Capability-gated affordances — behavior the platform may not offer (clipboard, share, fullscreen). Feature-detect once, declare the capability as state, reveal dependent controls by CSS.
  5. Latency elimination — making instant what navigation already does (reactive filters via route(cb, { match }) + request()). The page must stay whole without it.

Every module above rung 1 must pass the deletion test's module form: delete the file and the server-rendered baseline is whole. Live arrivals and faster updates may disappear; initial content and structure must not depend on browser enhancement.

Element-as-state-carrier

Many platform elements already carry state in their own attributes, with native CSS hooks. When the state genuinely lives on a specific element, use that — don't add a body[data-x] indirection:

| Element | Native state attribute | What you do | | --- | --- | --- | | <dialog> | [open] | el.setAttribute("open", "") + the substrate's dialog[open] CSS, or el.showModal() if you need the backdrop and focus trap | | <details> | [open] | Same shape; browser handles the disclosure UX | | <input>, <textarea> | [aria-invalid], [aria-required], [disabled] | Direct setAttribute; CSS targets :invalid, [disabled] | | <button> | [aria-pressed] (toggle state), [disabled] | Native focus/style for free | | <select> | The current value | Read via el.value; no body indirection needed |

The body[data-modal] indirection is correct when the state is a named enum the consumer controls (which modal is open, current page, theme). When the state genuinely lives on an element (is THIS dialog open?), let it live there.

Non-DOM EventTargets

on() is DOM delegation — closest(selector) against a container. Non-Element EventTargets have no selector to delegate against, and otm/prefer-on bans raw addEventListener everywhere. Distinguish privately owned 1:1 targets from shared broadcast targets:

  • Shared / broadcast targets (window, document lifecycle events such as visibilitychange, visualViewport, AbortSignal, MediaQueryList): use on.target(target, event, fn, { signal }) so sibling modules and multi-instance components compose without clobbering .onfoo properties.
  • Privately owned 1:1 targets (new Worker(), new FileReader()): handler properties (worker.onmessage = fn) remain clean because one owner created the target.
const dark = matchMedia("(prefers-color-scheme: dark)");
const off = on.target(dark, "change", (e) => {
  the("scheme", e.matches ? "dark" : "light");
});
off();

Sockets are their own case: otm/no-raw-websocket bans new WebSocket outright — use live().

Banned vocabulary, in spirit

If you're searching online for "how to subscribe to OTM state changes" or "OTM reactive system" — you're looking for something the framework doesn't have and won't add. The three mechanisms above are the whole story. Reactivity-by-CSS, imperative-by-handler, DRY-by-observer.

Patterns

Form intake

on("#todo-form", "submit", "form", (e) => {
  e.preventDefault();
  const data = the.form(e.target);                          // { task, tags: [...] }
  the($.clone("#todo-list", "#todo-item"), the.flat(data)); // task, tags-0, tags-1 → attrs
});

List rendering with i18n

<template id="post-card">
  <article data-item>
    <h2 data-text="title"></h2>
    <p data-i18n="posted_at" data-i18n-val=""></p>
  </article>
</template>
<section id="posts"></section>
for (const post of posts) {
  const el = $.clone("#posts", "#post-card");
  the(el, { title: post.title });
  const date = $(el, '[data-i18n="posted_at"]');
  date.setAttribute("data-i18n-val", new Date(post.created_at).toISOString());
  date.setAttribute("data-i18n-type", "date");
}
_t();

Routing (multi-page SPA)

route((path) => {
  the("page", path === "/" ? "home" : path.slice(1));
});
main > section { display: none; }
[data-page="home"]    main > section[data-route="home"]    { display: block; }
[data-page="about"]   main > section[data-route="about"]   { display: block; }
[data-page="contact"] main > section[data-route="contact"] { display: block; }

Hot dictionary swap

await the.boot({ persistKeys: ["theme", "lang"] });

on("nav", "click", "[data-lang]", async (_e, link) => {
  const lang = link.getAttribute("data-lang");
  the("lang", lang);        // persists — boot's resolution chain finds it on reload
  await the.boot({ locale: lang }); // uses the declared dictionary chain and source fallback
});

The the("lang", lang) write is what makes the preference survive reload: boot reads opted-in localStorage["otm:lang"] ahead of <html lang>. Without it, the selection reverts on refresh. Declare the translation endpoint and available dictionaries on the document; a source-only document simply retains its source text.

Namespaced state

// Two apps on the same origin can coexist:
await the.boot({ namespace: "dashboard" }); // localStorage keys: dashboard:theme, etc.

Cleanup with on() unsubscribe

const off = on("#modal", "click", "[data-action='close']", closeModal);
on.emit(document.body, "modal-closed");
off(); // detach when modal is destroyed

Fetch intake — server emits JSON, client renders

const res = await fetch("/api/posts");
const posts = await res.json();

$.cloneEach("#posts", "#post-card", posts, (el, post) => {
  the(el, { title: post.title });
});

$.cloneEach clears the container for you; replaceChildren() also clears it natively, and textContent = "" clears a literal-text outlet. The server can render real documents or supply data; otm/no-server-dom prohibits using browser-DOM emulation packages to run OTM outside the browser, not ordinary server rendering.

Literal document content

Document bodies are not UI state. Notes, logs, code, and generated output can use ordinary semantic HTML without data-text, data-i18n, or a new content marker. Keep localizable interface copy and state mirrors alongside them:

<article id="document">
  <h2 data-i18n="document_title">Document</h2>
  <p data-text="document-status">Ready</p>
  <pre id="document-body">Previously rendered content.</pre>
</article>

Given a literal string body from your application's request or stream boundary, insert it into the existing display outlet:

const outlet = $("#document-body");
if (outlet.textContent !== body) {
  outlet.textContent = body;
}

The DOM textContent setter inserts text, not parsed HTML: tags, entities, Markdown, Unicode, and line breaks remain literal. Do not pre-escape this string for HTML; server-rendered HTML still needs its normal contextual escaping. Use a display element, not an executable element such as <script>. innerText has rendered-text semantics and is not the exact-text path.

Compare against the live DOM before writing. Equal content leaves existing text nodes and native selection untouched, including split text nodes. Changed content replaces the outlet's children; an empty string clears them. This is not an editor, caret-preservation algorithm, or DOM reconciler. There is no hidden store or duplicate data-* body. Do not put data-text or data-i18n on the same outlet (or an owning ancestor) and give two writers ownership of its contents.

Already-sanitized rich fragments can use native replaceChildren(sanitizedFragment). Sanitization, allowed markup/URLs, and the fragment's trust boundary belong to the application; OTM neither sanitizes nor interprets raw HTML or Markdown. lang describes the actual content language. translate="no" is a translation policy, not a required content marker.

Routing with the.match

route(() => {
  const post = the.match("/posts/:slug");
  if (post) return renderPost(post.slug);

  const profile = the.match("/@:user");
  if (profile) return renderProfile(profile.user);

  if (location.pathname === "/") return renderHome();
});

Imperative dispatch from many sites (mechanism #3)

This is the case-3 pattern from The Discipline: the same state can be written from several places (user click, fetch error handler, boot replay, etc.) and all of them need the same imperative response. Observe the attribute once, dispatch from there:

new MutationObserver(() => {
  const wantModal = the("modal");
  for (const dialog of $$("dialog[open]")) {
    if (dialog.id !== `${wantModal}-modal`) dialog.close();
  }
  if (wantModal) $(`#${wantModal}-modal`)?.showModal();
}).observe(document.body, { attributes: true, attributeFilter: ["data-modal"] });

document.body is the allowed identifier under otm/no-document-query. Filter by attributeFilter to scope the observer narrowly.

Before reaching for this pattern, check whether CSS can do the job. If the response is purely visual (show/hide, color, layout), the CSS attribute selector is the right tool and the observer is overhead. Reserve MutationObserver for imperative APIs CSS can't express (showModal, focus, scrollIntoView, media controls, animation triggers).

Dynamic messages in the source language

Programmatic _t(key, options) returns the key when no loaded catalog supplies it; static DOM text is not a programmatic message template. Advertise a source-language catalog in data-available, or supply an inline dictionary when the application owns that catalog directly:

await the.boot({ locale: "en", dictionary: { greeting: "Hello, {name}!" } });
const greeting = _t("greeting", { name: "Alice" }); // "Hello, Alice!"

Use _t() to search the complete dictionary cascade; the.dictionary exposes only the primary catalog, so checking it at call sites bypasses fallback messages.

Server-side rendering (no extra API)

There's no SSR shim. Emit data-* attributes from the server:

<!-- rendered server-side -->
<body data-theme="dark" data-user="Alice">
  <h1 data-text="user">Alice</h1>
</body>

On the client:

await the.boot();   // localStorage values, if any, override the server-rendered attrs

The framework reads existing attributes via the(key) without modification, so server-rendered state is observable immediately. the.boot() only mutates keys opted into persistKeys that have stored values. Keep fallback text inside data-text carriers (<h1 data-text="user">Alice</h1>) when practical, so the initial document remains useful before enhancement.

Server content-engine & agentic composition

OTM is designed to compose cleanly with any upstream server-side content engine — Markdown → HTML filters (goldmark, comrak, Pandoc, Eleventy, Hugo), structured-data templates, or database-backed SSR — without client-side Markdown rendering or hydration:

  1. The server renders plain semantic HTML from your canonical documents (.md, JSON, DB rows). on_the_money/css/schema styles every standard Markdown element (<h1>–<h6>, <p>, <table>, <blockquote>, <pre><code>, <dl>, <hr>, <figure>) classlessly, and ordinary prose needs neither data-i18n nor data-text mirrors.
  2. The server delivers canonical text/markdown to agents (via .md URLs and/or HTTP Accept: text/markdown content negotiation in your server or reverse proxy), linked from HTML with <link rel="alternate" type="text/markdown" href="..."> and indexed at /llms.txt.
  3. Sibling landmarks carry explicit accessible names (aria-label / aria-labelledby), giving screen readers, browser agents, and classless CSS (nav[aria-label="Primary"]) unambiguous hooks without class names.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Hello World</title>
  <link rel="alternate" type="text/markdown" href="/posts/hello.md">
  <link rel="stylesheet" href="/assets/index.css">
</head>
<body>
  <header><nav aria-label="Primary"><a href="/">Home</a></nav></header>
  <main>
    <article>
      <h1>Hello World</h1>
      <p>Server-rendered semantic HTML from canonical Markdown or structured data.</p>
    </article>
  </main>
  <footer><nav aria-label="Footer"><a href="/llms.txt">llms.txt</a></nav></footer>
</body>
</html>

For two-stage static pipelines (your-filter ./content ./stage && npx otm-build ./stage --out ./dist), otm-build keeps <link rel="alternate" type="text/markdown"> intact, copies .md companions and llms.txt straight through, and keeps the full semantic stylesheet intact by default.

NOT in scope: OTM ships no Markdown or frontmatter parser, no HTML sanitizer, no SSG/layout engine, no otm-build filter plugin API, no server HTTP Accept: text/markdown middleware, and no speculative pre-standard browser-agent runtime APIs.

Lint stack

on_the_money ships a three-tool stack. Each layer covers what the others can't.

1. JavaScript — ESLint + bundled plugin

The ESLint plugin and config ship inside on_the_money itself. No separate eslint-plugin-otm package — import via subpath.

npm install -D eslint eslint-plugin-no-unsanitized
// eslint.config.js
import otm from "on_the_money/eslint-config";
import nounsanitized from "eslint-plugin-no-unsanitized";

export default [
  ...otm,
  nounsanitized.configs.recommended,
];

| Rule | Source | Behavior | | --- | --- | --- | | otm/prefer-on | bundled in on_the_money | Ban addEventListener; require on(parent, event, selector, handler) or on.target(target, event, handler, options?). | | otm/flat-state | bundled in on_the_money | Ban nested objects/arrays in the() calls. | | otm/kebab-state-keys | bundled in on_the_money | Require canonical lowercase kebab-case keys in the() and the.boot({ persistKeys }). | | otm/prefer-submit | bundled in on_the_money | Warn on on(..., "click", "button", ...) or [type="submit"] for form data (allows explicit button[data-action] and button[type="button"]). | | otm/no-style-mutation | bundled in on_the_money | Ban el.style.* = .... | | otm/no-server-dom | bundled in on_the_money | Ban imports of linkedom, jsdom, cheerio, parse5, etc.; no out-of-browser OTM rendering. | | otm/no-document-query | bundled in on_the_money | Ban document.querySelector/getElementById/createElement/etc.; use $/$$/$.clone. Use // eslint-disable-next-line otm/no-document-query for legitimate bridge code (MutationObserver targets, etc.). | | no-unsanitized/no-inner-html | eslint-plugin-no-unsanitized | Ban innerHTML/outerHTML. | | no-unsanitized/method | eslint-plugin-no-unsanitized | Ban document.write, insertAdjacentHTML. |

The recommended config matches **/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx} — your TypeScript files are covered if you bring a TS-aware parser like @typescript-eslint/parser. OTM's rules read AST nodes that don't depend on type info, but the parser still has to understand the syntax. Test files (**/*.test.*) are exempt from no-server-dom and no-document-query — tests drive the DOM directly through the on_the_money/test harness.

2. CSS — Stylelint + bundled plugin

Same pattern: the Stylelint plugin and config ship inside on_the_money. No separate stylelint-plugin-otm package. Supports Stylelint >=16 (verified with Stylelint 18 + stylelint-config-standard 41 on Node >=24.15.0).

npm install -D stylelint stylelint-config-standard
// stylelint.config.js
import otm from "on_the_money/stylelint-config";

export default {
  extends: ["stylelint-config-standard"],
  ...otm,
};

| Rule | Source | Behavior | | --- | --- | --- | | otm/prefer-attribute-selector | bundled in on_the_money | Ban .class selectors; use [data-state="..."]. | | otm/layer-discipline | bundled in on_the_money | Enforce 5-S @layer wrappers and layer boundaries across structure.css, style.css, and state.css (plus @layer blocks and unlayered rules in layered stylesheets). | | declaration-no-important | stylelint built-in | Ban !important. |

3. HTML / cross-file — otm-lint

npx otm-lint --check ./src

| Rule | Forbidden | Use instead | | --- | --- | --- | | HTML-017 | <div data-action="..."> without role/tabindex | Use a <button> or other interactive element. | | HTML-023 | A declared <meta name="i18n"> has no dictionary path | Provide content, or omit the meta entirely for a source-only document. | | HTML-024 | data-available="..." doesn't match locales folder | Keep the manifest aligned with the actual locale files. | | HTML-025 | data-i18n-type="currency" without data-i18n-currency | _t() throws at runtime without an explicit ISO 4217 code — declare it on the element. | | HTML-026 | Invalid source, available, or fallback locale identifier | Use Unicode locale tags accepted by Intl.Locale, such as fr-CA or sr-Latn. | | HTML-027 | Active date formatting has a missing or invalid value | Supply ISO date text in data-i18n-val before activating data-i18n-type="date". | | HTML-028 | Multiple <nav> landmarks in one document without unique aria-label / aria-labelledby | Name each sibling