stimeo-ui 0.1.0-beta.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +107 -0
- package/README.md +6 -6
- package/dist/controllers/auto_submit_controller.js +56 -21
- package/dist/controllers/auto_submit_controller.js.map +1 -1
- package/dist/controllers/character_counter_controller.js +52 -15
- package/dist/controllers/character_counter_controller.js.map +1 -1
- package/dist/controllers/combobox_controller.d.ts +6 -2
- package/dist/controllers/combobox_controller.js +64 -3
- package/dist/controllers/combobox_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.d.ts +13 -6
- package/dist/controllers/command_palette_controller.js +256 -39
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.js +107 -8
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/context_menu_controller.d.ts +11 -6
- package/dist/controllers/context_menu_controller.js +191 -13
- package/dist/controllers/context_menu_controller.js.map +1 -1
- package/dist/controllers/countdown_controller.d.ts +2 -2
- package/dist/controllers/countdown_controller.js +2 -2
- package/dist/controllers/countdown_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.js +107 -8
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/dropdown_controller.d.ts +9 -6
- package/dist/controllers/dropdown_controller.js +139 -16
- package/dist/controllers/dropdown_controller.js.map +1 -1
- package/dist/controllers/focus_controller.js +107 -8
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js +2 -2
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/hover_card_controller.d.ts +15 -12
- package/dist/controllers/hover_card_controller.js +103 -27
- package/dist/controllers/hover_card_controller.js.map +1 -1
- package/dist/controllers/intersection_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/listbox_controller.js +1 -0
- package/dist/controllers/listbox_controller.js.map +1 -1
- package/dist/controllers/menu_controller.d.ts +18 -11
- package/dist/controllers/menu_controller.js +181 -8
- package/dist/controllers/menu_controller.js.map +1 -1
- package/dist/controllers/otp_controller.js +62 -22
- package/dist/controllers/otp_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.d.ts +3 -2
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.js +3 -3
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/popover_controller.d.ts +18 -10
- package/dist/controllers/popover_controller.js +118 -27
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/controllers/scroll_area_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/sortable_controller.d.ts +2 -2
- package/dist/controllers/sortable_controller.js +1 -1
- package/dist/controllers/sortable_controller.js.map +1 -1
- package/dist/controllers/sticky_observer_controller.js.map +1 -1
- package/dist/controllers/tabs_controller.d.ts +1 -2
- package/dist/controllers/tabs_controller.js.map +1 -1
- package/dist/controllers/toast_controller.d.ts +7 -9
- package/dist/controllers/toast_controller.js +108 -29
- package/dist/controllers/toast_controller.js.map +1 -1
- package/dist/controllers/tooltip_controller.d.ts +15 -18
- package/dist/controllers/tooltip_controller.js +148 -42
- package/dist/controllers/tooltip_controller.js.map +1 -1
- package/dist/index.d.ts +44 -14
- package/dist/index.js +847 -349
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +6 -6
- package/dist/inspector/manifest.json +16 -3
- package/package.json +7 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/inspector/erb.ts","../../src/inspector/extract.ts","../../src/inspector/html_parser.ts","../../src/inspector/types.ts","../../src/inspector/check.ts","../../src/inspector/examples.ts","../../src/inspector/files.ts","../../src/inspector/manifest_io.ts","../../src/inspector/cli.ts","../../src/inspector/mcp/prompts.ts","../../src/inspector/mcp/tools.ts","../../src/in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<% %>`, `<%= %>`, `<%# %>`, plus the whitespace-trimming\n * variants `<%- -%>` — is replaced with spaces. Newlines inside the tag are\n * preserved so that 1-based line/column positions used in diagnostics line up\n * with the original source.\n *\n * Because ERB is blanked rather than interpreted, dynamically-generated markup\n * is naturally excluded from checking: a dynamic identifier such as\n * `data-controller=\"<%= id %>\"` collapses to an empty attribute value and a\n * dynamic attribute name such as `data-<%= x %>-target` no longer matches the\n * `stimeo--*` patterns. This is the intended \"dynamic attributes are out of\n * scope\" behavior.\n *\n * @param source - Raw HTML/ERB source.\n * @returns The source with all ERB tags replaced by position-preserving spaces.\n */\nexport function neutralizeErb(source: string): string {\n return source.replace(/<%[\\s\\S]*?%>/g, (match) => match.replace(/[^\\n]/g, \" \"));\n}\n","/**\n * Pure helpers for recognizing `stimeo--*` attributes within parsed markup.\n *\n * These functions know nothing about files or the manifest — they only decode\n * Stimulus's attribute conventions, scoped strictly to the `stimeo--`\n * namespace so a consumer's own controllers are never inspected.\n */\n\nconst NAMESPACE_PREFIX = \"stimeo--\";\n\n/**\n * Converts a Stimulus value name to its attribute token, mirroring Stimulus's\n * own dasherize (e.g. `rootMargin` → `root-margin`).\n */\nexport function dasherize(value: string): string {\n return value.replace(/([A-Z])/g, (_match, char: string) => `-${char.toLowerCase()}`);\n}\n\n/** Extracts the `stimeo--*` identifiers listed in a `data-controller` value.\n * Duplicates are collapsed (Stimulus connects a repeated identifier once), which\n * keeps downstream scope-based diagnostics from being reported multiple times. */\nexport function controllerIdentifiers(dataControllerValue: string): string[] {\n const seen = new Set<string>();\n for (const token of dataControllerValue.split(/\\s+/)) {\n if (token.startsWith(NAMESPACE_PREFIX)) seen.add(token);\n }\n return [...seen];\n}\n\n/**\n * If `attrName` is an Stimeo target attribute (`data-{identifier}-target`),\n * returns the controller identifier; otherwise `null`.\n */\nexport function parseTargetAttr(attrName: string): string | null {\n const match = /^data-(stimeo--[a-z0-9][a-z0-9-]*)-target$/.exec(attrName);\n return match?.[1] ?? null;\n}\n\n/** Result of decoding a `data-{identifier}-{value}-value` attribute. */\nexport interface ParsedValueAttr {\n /** Resolved identifier, or `null` when it matches no known controller. */\n readonly identifier: string | null;\n /** The dasherized value token (e.g. `root-margin`), best-effort when unresolved. */\n readonly valueToken: string;\n}\n\n/**\n * Decodes an Stimeo value attribute (`data-{identifier}-{value}-value`).\n *\n * Identifiers may themselves contain hyphens (e.g. `stimeo--command-palette`),\n * so the boundary between identifier and value name is ambiguous from the\n * attribute name alone. We disambiguate against the set of known identifiers,\n * preferring the longest match.\n *\n * @param attrName - The lowercased attribute name.\n * @param knownIdentifiers - All identifiers present in the manifest.\n * @returns The decoded attribute, or `null` if it is not an Stimeo value attr.\n */\nexport function parseValueAttr(\n attrName: string,\n knownIdentifiers: readonly string[],\n): ParsedValueAttr | null {\n const match = /^data-(stimeo--[a-z0-9-]+)-value$/.exec(attrName);\n if (!match) return null;\n const inner = match[1] ?? \"\"; // identifier + \"-\" + valueToken\n\n let best: { identifier: string; valueToken: string } | null = null;\n for (const id of knownIdentifiers) {\n if (inner.startsWith(`${id}-`)) {\n const valueToken = inner.slice(id.length + 1);\n if (valueToken.length > 0 && (!best || id.length > best.identifier.length)) {\n best = { identifier: id, valueToken };\n }\n }\n }\n if (best) return best;\n\n // Unknown identifier: best-effort split at the first segment after the prefix.\n const rest = inner.slice(NAMESPACE_PREFIX.length);\n const dash = rest.indexOf(\"-\");\n const identifierGuess = dash === -1 ? inner : `${NAMESPACE_PREFIX}${rest.slice(0, dash)}`;\n const valueGuess = dash === -1 ? \"\" : rest.slice(dash + 1);\n return { identifier: null, valueToken: valueGuess || identifierGuess };\n}\n\n/** An Stimeo `data-action` descriptor decoded into its controller and method. */\nexport interface ActionDescriptor {\n /** The `stimeo--*` controller identifier (e.g. `stimeo--menu`). */\n readonly identifier: string;\n /** The action method name after `#` (e.g. `toggle`), or `\"\"` if absent. */\n readonly method: string;\n}\n\n/**\n * Decodes the Stimeo `data-action` descriptors in an attribute value, e.g.\n * `click->stimeo--menu#toggle keydown->stimeo--menu#onItemKeydown` yields one\n * entry per descriptor. Non-`stimeo--` controllers are skipped (their action\n * surface is out of scope). The method name is read up to the first action\n * option (`:prevent`, `:stop`, …), mirroring Stimulus's descriptor grammar.\n */\nexport function actionDescriptors(dataActionValue: string): ActionDescriptor[] {\n const descriptors: ActionDescriptor[] = [];\n for (const descriptor of dataActionValue.split(/\\s+/)) {\n const hash = descriptor.indexOf(\"#\");\n if (hash === -1) continue;\n let lhs = descriptor.slice(0, hash);\n const arrow = lhs.indexOf(\"->\");\n if (arrow !== -1) lhs = lhs.slice(arrow + 2);\n if (!lhs.startsWith(NAMESPACE_PREFIX)) continue;\n const method = /^[a-zA-Z_$][\\w$]*/.exec(descriptor.slice(hash + 1))?.[0] ?? \"\";\n descriptors.push({ identifier: lhs, method });\n }\n return descriptors;\n}\n\n/**\n * Extracts the `stimeo--*` controller identifiers referenced in a\n * `data-action` value, e.g. `click->stimeo--menu#toggle` yields\n * `[\"stimeo--menu\"]`. Convenience wrapper over {@link actionDescriptors}.\n */\nexport function actionIdentifiers(dataActionValue: string): string[] {\n return actionDescriptors(dataActionValue).map((d) => d.identifier);\n}\n\n/** Whether an attribute name belongs to the Stimeo namespace. */\nexport function isStimeoDataAttr(attrName: string): boolean {\n return attrName.startsWith(`data-${NAMESPACE_PREFIX}`);\n}\n","/**\n * A minimal, dependency-free HTML tokenizer/tree builder.\n *\n * The Inspector deliberately ships **zero runtime dependencies** beyond the\n * Stimulus peer (see project invariants), so rather than pull in a DOM library\n * we build just enough of a tree to answer the only questions the checker asks:\n * \"which `stimeo--*` attributes exist, where, and inside which controller\n * scope?\". The parser is intentionally lenient — real-world ERB output has\n * unclosed tags and stray markup — and never throws.\n *\n * It is **not** a spec-compliant HTML parser and should not be used for\n * anything beyond static attribute inspection.\n */\n\n/** A parsed attribute, with the source position of its name. */\nexport interface ParsedAttr {\n /** Lowercased attribute name (HTML attribute names are case-insensitive). */\n readonly name: string;\n /** Attribute value (without surrounding quotes); empty for boolean attrs. */\n readonly value: string;\n /** 1-based line of the attribute name. */\n readonly line: number;\n /** 1-based column of the attribute name. */\n readonly column: number;\n /**\n * Absolute source offset where the value text begins (inside the quotes);\n * absent for boolean attributes. ERB neutralization preserves offsets, so a\n * consumer can map the range back onto the *raw* source — this is how the\n * checker tells an authored value from a dynamically-generated one.\n */\n readonly valueStart?: number;\n /** Absolute source offset just past the value text; see {@link valueStart}. */\n readonly valueEnd?: number;\n}\n\n/** An element node in the lenient tree. */\nexport interface ElementNode {\n /** Lowercased tag name; the synthetic root uses `#root`. */\n readonly tag: string;\n readonly attrs: readonly ParsedAttr[];\n readonly children: ElementNode[];\n parent: ElementNode | null;\n /** 1-based line of the tag's `<`. */\n readonly line: number;\n /** 1-based column of the tag's `<`. */\n readonly column: number;\n}\n\n/** Elements that never have children and so are never pushed onto the stack. */\nconst VOID_ELEMENTS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Elements whose content is raw text (no nested elements to parse). */\nconst RAW_TEXT_ELEMENTS = new Set([\"script\", \"style\", \"textarea\", \"title\"]);\n\nconst WHITESPACE = new Set([\" \", \"\\t\", \"\\n\", \"\\r\", \"\\f\"]);\n\n/** Maps absolute string offsets to 1-based line/column positions. */\nclass PositionIndex {\n readonly #lineStarts: number[] = [0];\n\n constructor(source: string) {\n for (let i = 0; i < source.length; i++) {\n if (source[i] === \"\\n\") this.#lineStarts.push(i + 1);\n }\n }\n\n at(offset: number): { line: number; column: number } {\n // Binary search for the last line start that is <= offset.\n let lo = 0;\n let hi = this.#lineStarts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if ((this.#lineStarts[mid] ?? 0) <= offset) lo = mid;\n else hi = mid - 1;\n }\n return { line: lo + 1, column: offset - (this.#lineStarts[lo] ?? 0) + 1 };\n }\n}\n\n/**\n * Parses HTML (already ERB-neutralized) into a lenient element tree.\n *\n * @param source - HTML source to parse.\n * @returns The synthetic `#root` node whose children are the top-level elements.\n */\nexport function parseHtml(source: string): ElementNode {\n const pos = new PositionIndex(source);\n const len = source.length;\n /** Bounds-safe character access (out of range yields an empty string). */\n const ch = (k: number): string => (k >= 0 && k < len ? (source[k] as string) : \"\");\n\n const root: ElementNode = {\n tag: \"#root\",\n attrs: [],\n children: [],\n parent: null,\n line: 1,\n column: 1,\n };\n const stack: ElementNode[] = [root];\n let i = 0;\n\n const top = (): ElementNode => stack[stack.length - 1] as ElementNode;\n\n while (i < len) {\n if (ch(i) !== \"<\") {\n i++;\n continue;\n }\n\n const next = ch(i + 1);\n\n // Comment: <!-- ... -->\n if (source.startsWith(\"<!--\", i)) {\n const end = source.indexOf(\"-->\", i + 4);\n i = end === -1 ? len : end + 3;\n continue;\n }\n // Markup declaration (<!DOCTYPE ...>) or processing instruction (<? ... ?>).\n if (next === \"!\" || next === \"?\") {\n const end = source.indexOf(\">\", i);\n i = end === -1 ? len : end + 1;\n continue;\n }\n // End tag: </name>\n if (next === \"/\") {\n let j = i + 2;\n let name = \"\";\n while (j < len && ch(j) !== \">\" && !WHITESPACE.has(ch(j))) {\n name += ch(j);\n j++;\n }\n const end = source.indexOf(\">\", j);\n i = end === -1 ? len : end + 1;\n closeTag(stack, name.toLowerCase());\n continue;\n }\n // Not a tag start (e.g. a stray \"<\"); treat as text.\n if (!/[a-zA-Z]/.test(next)) {\n i++;\n continue;\n }\n\n // Start tag.\n const tagStart = i;\n let j = i + 1;\n let tagName = \"\";\n while (j < len && !WHITESPACE.has(ch(j)) && ch(j) !== \">\" && ch(j) !== \"/\") {\n tagName += ch(j);\n j++;\n }\n const lowerTag = tagName.toLowerCase();\n const attrs: ParsedAttr[] = [];\n\n // Parse attributes until the tag closes.\n let selfClosing = false;\n while (j < len) {\n while (j < len && WHITESPACE.has(ch(j))) j++;\n if (j >= len) break;\n if (ch(j) === \">\") {\n j++;\n break;\n }\n if (ch(j) === \"/\") {\n selfClosing = true;\n j++;\n continue;\n }\n\n // Attribute name.\n const nameStart = j;\n let attrName = \"\";\n while (j < len && !WHITESPACE.has(ch(j)) && ch(j) !== \"=\" && ch(j) !== \">\" && ch(j) !== \"/\") {\n attrName += ch(j);\n j++;\n }\n\n let attrValue = \"\";\n let valueStart: number | undefined;\n let valueEnd: number | undefined;\n // Optional value.\n let k = j;\n while (k < len && WHITESPACE.has(ch(k))) k++;\n if (ch(k) === \"=\") {\n k++;\n while (k < len && WHITESPACE.has(ch(k))) k++;\n const quote = ch(k);\n if (quote === '\"' || quote === \"'\") {\n k++;\n const valStart = k;\n while (k < len && ch(k) !== quote) k++;\n attrValue = source.slice(valStart, k);\n valueStart = valStart;\n valueEnd = k;\n k++; // skip closing quote\n } else {\n const valStart = k;\n while (k < len && !WHITESPACE.has(ch(k)) && ch(k) !== \">\") k++;\n attrValue = source.slice(valStart, k);\n valueStart = valStart;\n valueEnd = k;\n }\n j = k;\n }\n\n if (attrName.length > 0) {\n const p = pos.at(nameStart);\n attrs.push({\n name: attrName.toLowerCase(),\n value: attrValue,\n line: p.line,\n column: p.column,\n valueStart,\n valueEnd,\n });\n }\n }\n\n const startPos = pos.at(tagStart);\n const node: ElementNode = {\n tag: lowerTag,\n attrs,\n children: [],\n parent: top(),\n line: startPos.line,\n column: startPos.column,\n };\n top().children.push(node);\n\n i = j;\n\n if (selfClosing || VOID_ELEMENTS.has(lowerTag)) {\n continue;\n }\n\n if (RAW_TEXT_ELEMENTS.has(lowerTag)) {\n // Skip raw-text content so `<` inside scripts/styles is not parsed as markup.\n const closeNeedle = `</${lowerTag}`;\n const idx = source.toLowerCase().indexOf(closeNeedle, i);\n if (idx === -1) {\n i = len;\n } else {\n const gt = source.indexOf(\">\", idx);\n i = gt === -1 ? len : gt + 1;\n }\n continue;\n }\n\n stack.push(node);\n }\n\n return root;\n}\n\n/** Pops the stack down to (and including) the nearest matching open tag. */\nfunction closeTag(stack: ElementNode[], name: string): void {\n for (let depth = stack.length - 1; depth >= 1; depth--) {\n if (stack[depth]?.tag === name) {\n stack.length = depth;\n return;\n }\n }\n // No matching open tag — ignore the stray end tag.\n}\n\n/** Depth-first walk over every element node (excluding the synthetic root). */\nexport function walk(root: ElementNode, visit: (node: ElementNode) => void): void {\n for (const child of root.children) {\n visit(child);\n walk(child, visit);\n }\n}\n","/**\n * Shared types for the Stimeo Inspector CLI (`stimeo check`).\n *\n * The Inspector statically checks HTML/ERB against a *manifest* describing the\n * official `stimeo--` controllers. The same engine powers both the project's own\n * contract checks (e.g. `stimeo check app/views`) and the\n * user-facing product feature; it is therefore intentionally input-path\n * agnostic.\n */\n\n/**\n * Per-controller manifest entry.\n *\n * `targets` and `values` are reflected from the controller class\n * (`static targets` / `static values`). `actions` and `events` are reflected\n * from co-located `static actions` / `static events` declarations — Stimulus\n * keeps no registry of action methods, and TypeScript `private` survives on the\n * prototype, so the public action/event surface cannot be told apart from\n * internal helpers by reflection alone; it must be declared explicitly in the\n * implementation. `requiredTargets` is a hand-written structure rule (Stimulus\n * reflection cannot express \"required\").\n */\nexport interface ControllerManifest {\n /** Target names declared via `static targets`. */\n readonly targets: readonly string[];\n /** Value names (camelCase) declared via `static values`. */\n readonly values: readonly string[];\n /**\n * Public action method names declared via `static actions`, wired by\n * consumers as `data-action=\"…-><identifier>#<action>\"`.\n */\n readonly actions: readonly string[];\n /**\n * Logical event names declared via `static events`, dispatched as\n * `<identifier>:<event>` (Stimulus `this.dispatch(\"<event>\")`).\n */\n readonly events: readonly string[];\n /** Targets that must be present at least once inside the controller scope. */\n readonly requiredTargets: readonly string[];\n /**\n * Accessibility requirements the *consumer's markup* must satisfy (stage 3):\n * ARIA attributes the controller does **not** set at runtime and therefore\n * relies on the author to provide (e.g. a dialog's `role`/`aria-modal`/name).\n * Attributes the controller manages itself (e.g. tabs' `aria-selected`) are\n * deliberately excluded — requiring them would be noise.\n */\n readonly a11y: readonly A11yRequirement[];\n /**\n * Keyboard prerequisites (stage 3, schema v4): targets whose documented\n * contract makes the *author* responsible for focusability — the controller\n * moves focus (or relies on the Tab order) but never writes `tabindex` for\n * them. Each listed target must be natively focusable or carry `tabindex`.\n * Targets whose controller initializes a roving tabindex on connect (tabs,\n * toolbar, radio group, …) are deliberately excluded.\n */\n readonly keyboard: readonly KeyboardRequirement[];\n /**\n * Author-futile attributes (stage 3, schema v4): ARIA the controller\n * recomputes wholesale at runtime, where an authored value can neither\n * survive nor serve as pre-connect initial state (e.g. a combobox input's\n * `aria-activedescendant`). Authoring one is reported as a *warning*.\n * Attributes whose authored value is a legitimate initial (`aria-expanded`,\n * `aria-checked`, `aria-valuenow`, …) are deliberately excluded.\n */\n readonly managedAria: readonly ManagedAriaRule[];\n /**\n * Conditional cross-controller composition rules (stage 3, schema v5):\n * value-alignment contracts between this controller and a co-located\n * companion (e.g. sortable's sort axis vs roving's `orientation`). Prose-only\n * before v5, where a dropped or misaligned value silently broke keyboard\n * interaction while `stimeo check` passed.\n */\n readonly compositions: readonly CompositionRule[];\n}\n\n/**\n * A single accessibility requirement on a controller's markup (Inspector\n * stage 3). At least one of {@link attrs} must be present on the\n * {@link target} element; when {@link values} is given, the present\n * attribute's value must be one of them. {@link or} widens the requirement\n * with alternative attribute/value groups — the requirement is satisfied when\n * *any* group is (schema v4; e.g. `role=\"status\"` **or** `aria-live`).\n */\nexport interface A11yRequirement {\n /**\n * Target name the requirement applies to; the empty string `\"\"` means the\n * controller's own scope element (the `data-controller` node).\n */\n readonly target: string;\n /**\n * Candidate attribute names — at least one must be present. A list expresses\n * \"any of\" (e.g. `aria-labelledby` *or* `aria-label` for an accessible name).\n */\n readonly attrs: readonly string[];\n /** Allowed values for the matched attribute; omit to accept any value. */\n readonly values?: readonly string[];\n /**\n * Alternative attribute groups, each with its **own** allowed-value set —\n * something `attrs` alone cannot express (its `values` apply to every listed\n * attribute). A present attribute with a wrong value is still reported even\n * when another group is satisfied: an invalid authored value is an error in\n * its own right (e.g. `aria-live=\"off\"` silencing a satisfied `role=\"status\"`).\n */\n readonly or?: readonly A11yAlternative[];\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/** One alternative attribute group of an {@link A11yRequirement} (`or`). */\nexport interface A11yAlternative {\n /** Candidate attribute names — at least one must be present. */\n readonly attrs: readonly string[];\n /** Allowed values for the matched attribute; omit to accept any value. */\n readonly values?: readonly string[];\n}\n\n/**\n * A keyboard prerequisite (stage 3, schema v4): every present element of\n * {@link target} must be reachable by keyboard. What \"reachable\" means depends\n * on how the controller drives focus, expressed by {@link reach}:\n *\n * - `\"tab\"` (Tab stop): the element is a steady tab stop the user reaches with\n * Tab, so it must be natively tab-focusable (`button`, `input` except\n * `type=\"hidden\"`, `select`, `textarea`, `summary`, `a[href]`, `area[href]`,\n * or `contenteditable`) **or** carry `tabindex=\"0\"` (any non-negative value).\n * A `tabindex=\"-1\"` removes it from the Tab order and therefore **fails** —\n * this is the case a mere \"has tabindex\" presence check would miss.\n * - `\"focus\"` (roving / programmatic): the controller moves focus with\n * `element.focus()`, so the element only has to be focusable *at all* —\n * natively focusable **or** carrying any valid `tabindex` (including the\n * roving `-1`).\n *\n * Only the per-element floor is checked; the roving set-level invariant\n * (\"exactly one item is `tabindex=\"0\"`\") is runtime state owned by the\n * controller and deliberately out of scope.\n */\nexport interface KeyboardRequirement {\n /** Target name the requirement applies to (never the scope element). */\n readonly target: string;\n /**\n * How the user reaches the target. Defaults to `\"tab\"` (the common case —\n * most operation points are steady Tab stops); set `\"focus\"` only for\n * targets the controller roves via programmatic focus.\n */\n readonly reach?: \"tab\" | \"focus\";\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/**\n * An author-futile attribute rule (stage 3, schema v4): authoring any of\n * {@link attrs} on the {@link target} element draws a `managed-aria`\n * **warning** — the controller recomputes the attribute wholesale, so the\n * authored value is dead weight that misleads readers of the markup.\n */\nexport interface ManagedAriaRule {\n /**\n * Target name the rule applies to; the empty string `\"\"` means the\n * controller's own scope element.\n */\n readonly target: string;\n /** Attribute names the controller owns outright. */\n readonly attrs: readonly string[];\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/**\n * A conditional cross-controller composition rule (stage 3, schema v5): when a\n * companion controller is co-located on one of the host's elements, one of the\n * companion's values must align with a value of the host. The rule fires only\n * when {@link coController} is actually declared there — composition itself\n * stays optional (whether to compose is the author's call; the rule only\n * guards *how*).\n *\n * Both sides are compared by their **effective** value — the authored\n * attribute, or the declared default when the attribute is absent — because\n * the misalignments these rules exist for are default asymmetries (e.g.\n * sortable defaults its `orientation` to `vertical` while roving defaults to\n * `horizontal`, so a bare composition is silently broken). The defaults are\n * duplicated here from the controllers' `static values`; a manifest test\n * guards them against drift.\n */\nexport interface CompositionRule {\n /**\n * Host target whose element hosts the companion; the empty string `\"\"`\n * means the controller's own scope element.\n */\n readonly target: string;\n /**\n * Check the scope element when {@link target} is absent — for optional\n * container targets whose documented fallback is the scope element itself\n * (e.g. sortable's `list`).\n */\n readonly fallbackToScope?: boolean;\n /** Companion controller identifier expected in the element's `data-controller`. */\n readonly coController: string;\n /**\n * Condition on the host's own value (read from the scope element); omit for\n * unconditional rules. The rule applies only when the host's effective\n * value is one of `equals`.\n */\n readonly when?: {\n /** Host value name (camelCase, as declared in `static values`). */\n readonly value: string;\n /** Effective host values that arm the rule. */\n readonly equals: readonly string[];\n /** The host value's declared default, used when the attribute is absent. */\n readonly default: string;\n };\n /** Requirement on the companion's value (read from the companion's element). */\n readonly require: {\n /** Companion value name (camelCase, as declared in `static values`). */\n readonly value: string;\n /**\n * Allowed effective values, **ordered**: the first entry is the canonical\n * alignment and feeds the machine fix when an authored value is wrong.\n */\n readonly oneOf: readonly string[];\n /** The companion value's declared default, used when the attribute is absent. */\n readonly default: string;\n };\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/**\n * The bundled manifest. `schemaVersion` tracks the manifest *format*;\n * `packageVersion` tracks the `stimeo-ui` release it was generated from so a\n * consumer can confirm the check matches their installed version.\n */\nexport interface Manifest {\n readonly schemaVersion: number;\n readonly packageVersion: string;\n /** Keyed by controller identifier, e.g. `stimeo--menu`. */\n readonly controllers: Readonly<Record<string, ControllerManifest>>;\n}\n\n/** Hand-written structure rules, merged into the reflected manifest. */\nexport type StructureRules = Readonly<\n Record<string, { readonly requiredTargets?: readonly string[] }>\n>;\n\n/** Hand-written accessibility rules (stage 3), merged into the manifest. */\nexport type A11yRules = Readonly<Record<string, readonly A11yRequirement[]>>;\n\n/** Hand-written keyboard prerequisites (stage 3), merged into the manifest. */\nexport type KeyboardRules = Readonly<Record<string, readonly KeyboardRequirement[]>>;\n\n/** Hand-written author-futile attribute rules, merged into the manifest. */\nexport type ManagedAriaRules = Readonly<Record<string, readonly ManagedAriaRule[]>>;\n\n/** Hand-written composition rules (stage 3), merged into the manifest. */\nexport type CompositionRules = Readonly<Record<string, readonly CompositionRule[]>>;\n\n/** Severity of a diagnostic. Only `error` affects the process exit code. */\nexport type DiagnosticSeverity = \"error\" | \"warning\";\n\n/**\n * Stable identifiers for the kinds of problems the Inspector reports. Useful\n * for testing, machine-readable output, and `data-stimeo-ignore` suppression\n * lists (which is why the set also exists as a runtime array).\n */\nexport const DIAGNOSTIC_CODES = [\n \"unknown-controller\",\n \"unknown-target\",\n \"unknown-value\",\n \"unknown-action-controller\",\n \"unknown-action-method\",\n \"orphan-target\",\n \"missing-required-target\",\n \"missing-aria\",\n \"invalid-aria-value\",\n \"keyboard-inaccessible\",\n \"unresolved-idref\",\n \"managed-aria\",\n \"composition-mismatch\",\n \"unknown-ignore-code\",\n] as const;\n\n/** See {@link DIAGNOSTIC_CODES}. */\nexport type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number];\n\n/**\n * A machine-applicable fix for a diagnostic: replace the source text in\n * `[start, end)` with `text`. Only emitted when the engine can compute the\n * exact range with confidence — a typo'd token inside an attribute value, or\n * a single-valued ARIA correction. Editors surface it as a quick fix; the\n * human-readable `suggestion` stays the fallback for everything else.\n */\nexport interface DiagnosticFix {\n /** Absolute source offset where the replacement starts. */\n readonly start: number;\n /** Absolute source offset just past the replaced text. */\n readonly end: number;\n /** Replacement text. */\n readonly text: string;\n /** Short imperative label for editor UI, e.g. `Replace with \"stimeo--menu\"`. */\n readonly title: string;\n}\n\n/** A single problem found in a source file. */\nexport interface Diagnostic {\n readonly code: DiagnosticCode;\n readonly severity: DiagnosticSeverity;\n readonly message: string;\n /** 1-based line where the problem was detected. */\n readonly line: number;\n /** 1-based column where the problem was detected. */\n readonly column: number;\n /**\n * Length in source characters of the anchored token starting at `column` —\n * the attribute name for attribute-anchored diagnostics, or the opening\n * `<tag` for element-anchored ones. Lets editors underline the exact token\n * instead of guessing a word boundary. Optional so hand-built or historical\n * reports without it stay valid; consumers should fall back to `1`.\n */\n readonly length?: number;\n /**\n * Optional fix suggestion (stage 4): the corrected attribute to add, or the\n * nearest known name for a likely typo. Rendered on its own line by the CLI.\n */\n readonly suggestion?: string;\n /** Machine-applicable replacement (stage 4), when one can be computed safely. */\n readonly fix?: DiagnosticFix;\n}\n\n/** Diagnostics grouped by the file they came from. */\nexport interface FileReport {\n readonly file: string;\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/**\n * Machine-readable result of `stimeo check --json`: the structured counterpart\n * of the human report, for editor tooling and CI. `files` lists only sources\n * that produced diagnostics; `ok` is\n * true when no error-severity diagnostic was found (mirrors the exit code).\n */\nexport interface CheckReport {\n /** True when no error-severity diagnostics were found. */\n readonly ok: boolean;\n /** Total number of HTML/ERB files scanned. */\n readonly checkedFiles: number;\n /** Count of error-severity diagnostics across all files. */\n readonly errorCount: number;\n /** Count of warning-severity diagnostics across all files. */\n readonly warningCount: number;\n /** Per-file reports, limited to files that produced at least one diagnostic. */\n readonly files: readonly FileReport[];\n}\n","import { neutralizeErb } from \"./erb\";\nimport {\n actionDescriptors,\n controllerIdentifiers,\n dasherize,\n isStimeoDataAttr,\n parseTargetAttr,\n parseValueAttr,\n} from \"./extract\";\nimport { type ElementNode, type ParsedAttr, parseHtml, walk } from \"./html_parser\";\nimport {\n type A11yAlternative,\n type A11yRequirement,\n DIAGNOSTIC_CODES,\n type Diagnostic,\n type DiagnosticCode,\n type DiagnosticFix,\n type DiagnosticSeverity,\n type Manifest,\n} from \"./types\";\n\n/**\n * The core Inspector engine: checks a single HTML/ERB source string against the\n * manifest and returns diagnostics. It is **input-path agnostic** — the same\n * function backs both the project's own contract checks and the user-facing CLI.\n *\n * The check runs in staged passes:\n * - **Stage 1 (names/spelling):** every `stimeo--*` controller, target, value,\n * and `data-action` controller **and method** must exist in the manifest.\n * - **Stage 2 (structure):** required targets must be present within their\n * controller scope, and targets must have an owning controller.\n * - **Stage 3 (accessibility):** ARIA the controller relies on but does not set\n * itself (e.g. a dialog's `role`/`aria-modal`/name) must be present on the\n * relevant target, with the expected value (alternative groups via `or`).\n * Three sibling passes extend it: **keyboard prerequisites** (declared\n * targets must be focusable), **managed-aria** (author-futile attributes the\n * controller owns draw warnings), and **idref resolution** (ARIA reference\n * attributes on scope/target elements must point at an id declared in the\n * same file — a *warning*, since a reference may legitimately cross a\n * partial boundary the checker cannot see).\n * - **Stage 4 (fix suggestions):** diagnostics carry a `suggestion` — the\n * nearest known name for a likely typo, or the exact ARIA to add.\n *\n * Any element may opt out via {@link IGNORE_ATTR} (`data-stimeo-ignore`): an\n * empty value suppresses every diagnostic anchored at the element or its\n * descendants; a whitespace-separated {@link DiagnosticCode} list narrows the\n * suppression to those codes. Unknown codes in the list are themselves\n * reported (`unknown-ignore-code`, never suppressible).\n *\n * @remarks\n * Scope is resolved within a single source string. A controller and its targets\n * split across separate Rails partials cannot be correlated, so stage-2 checks\n * assume self-contained markup (Stimeo's recommended demo/partial structure).\n * Server-rendered **fragments** — markup a controller fetches and appends at\n * runtime (Turbo Streams, `stimeo--feed` pages) — are the legitimate exception:\n * declare the runtime host with {@link FRAGMENT_ATTR} on the fragment root and\n * `orphan-target` is suppressed for that identifier (names are still checked).\n * ERB is neutralized first, so dynamically-generated attributes are skipped.\n *\n * @param source - Raw HTML/ERB source.\n * @param manifest - The bundled controller manifest to check against.\n * @returns Diagnostics sorted by line then column.\n */\nexport function checkSource(source: string, manifest: Manifest): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n const tree = parseHtml(neutralizeErb(source));\n const known = manifest.controllers;\n const knownIdentifiers = Object.keys(known);\n\n /** `[start, end)` offsets of every ERB tag in the raw source. */\n const erbRanges = [...source.matchAll(/<%[\\s\\S]*?%>/g)].map(\n (m) => [m.index ?? 0, (m.index ?? 0) + m[0].length] as const,\n );\n\n /**\n * Whether the attribute's value text was (even partially) ERB-generated.\n * Neutralization preserves offsets, so the parser's value range maps 1:1\n * onto the raw source.\n */\n const isDynamicValue = (attr: ParsedAttr): boolean => {\n const { valueStart, valueEnd } = attr;\n if (valueStart === undefined || valueEnd === undefined) return false;\n return erbRanges.some(([start, end]) => start < valueEnd && end > valueStart);\n };\n\n /** True when `node` or an ancestor opts out of `code` via the ignore attr. */\n const suppressed = (node: ElementNode, code: DiagnosticCode): boolean => {\n if (code === \"unknown-ignore-code\") return false; // meta-diagnostic: never suppressible\n let current: ElementNode | null = node;\n while (current && current.tag !== \"#root\") {\n const ignore = current.attrs.find((a) => a.name === IGNORE_ATTR);\n if (ignore) {\n const codes = ignore.value.trim();\n if (codes.length === 0 || codes.split(/\\s+/).includes(code)) return true;\n }\n current = current.parent;\n }\n return false;\n };\n\n /** Suppression-aware diagnostic sink; `owner` anchors the ignore lookup. */\n const report: Reporter = (owner, code, severity, message, at, suggestion, fix): void => {\n if (!suppressed(owner, code)) push(diagnostics, code, severity, message, at, suggestion, fix);\n };\n\n /** Controller scope registrations: a node declaring `data-controller`. */\n const scopes: Array<{ node: ElementNode; identifier: string }> = [];\n /** Target names found within each scope, keyed by scope node then identifier. */\n const presence = new Map<ElementNode, Map<string, Set<string>>>();\n /** Target *elements* per scope/identifier/target name, for stage-3 ARIA checks. */\n const targetNodes = new Map<ElementNode, Map<string, Map<string, ElementNode[]>>>();\n\n const recordPresence = (owner: ElementNode, identifier: string, target: string): void => {\n let byId = presence.get(owner);\n if (!byId) {\n byId = new Map();\n presence.set(owner, byId);\n }\n let set = byId.get(identifier);\n if (!set) {\n set = new Set();\n byId.set(identifier, set);\n }\n set.add(target);\n };\n\n const recordTargetNode = (\n owner: ElementNode,\n identifier: string,\n target: string,\n el: ElementNode,\n ): void => {\n let byId = targetNodes.get(owner);\n if (!byId) {\n byId = new Map();\n targetNodes.set(owner, byId);\n }\n let byName = byId.get(identifier);\n if (!byName) {\n byName = new Map();\n byId.set(identifier, byName);\n }\n const found = byName.get(target);\n if (found) found.push(el);\n else byName.set(target, [el]);\n };\n\n walk(tree, (node) => {\n for (const attr of node.attrs) {\n // --- suppression declaration: data-stimeo-ignore ---------------------\n if (attr.name === IGNORE_ATTR) {\n // Spell-check the code list so a typo'd suppression cannot silently\n // fail open. Reported directly: this meta-diagnostic is unsuppressible.\n for (const token of attr.value.split(/\\s+/).filter((t) => t.length > 0)) {\n if (!(DIAGNOSTIC_CODES as readonly string[]).includes(token)) {\n const best = nearestName(token, DIAGNOSTIC_CODES);\n push(\n diagnostics,\n \"unknown-ignore-code\",\n \"warning\",\n `Unknown diagnostic code \"${token}\" in ${IGNORE_ATTR}.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, token, best),\n );\n }\n }\n continue;\n }\n\n // --- fragment declaration: data-stimeo-fragment ----------------------\n if (attr.name === FRAGMENT_ATTR) {\n const identifiers = attr.value.split(/\\s+/).filter((token) => token.length > 0);\n if (identifiers.length === 0) {\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `\"${FRAGMENT_ATTR}\" must name the fragment's runtime host controller(s).`,\n attr,\n );\n }\n for (const identifier of identifiers) {\n if (!(identifier in known)) {\n const best = nearestName(identifier, knownIdentifiers);\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Fragment declaration references unknown Stimeo controller \"${identifier}\".`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, identifier, best),\n );\n }\n }\n continue;\n }\n\n // --- data-controller -------------------------------------------------\n if (attr.name === \"data-controller\") {\n for (const identifier of controllerIdentifiers(attr.value)) {\n if (identifier in known) {\n scopes.push({ node, identifier });\n } else {\n const best = nearestName(identifier, knownIdentifiers);\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Unknown Stimeo controller \"${identifier}\".`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, identifier, best),\n );\n }\n }\n continue;\n }\n\n // --- target attribute: data-{identifier}-target ----------------------\n const targetIdentifier = parseTargetAttr(attr.name);\n if (targetIdentifier) {\n const controller = known[targetIdentifier];\n if (!controller) {\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Target attribute \"${attr.name}\" references unknown Stimeo controller \"${targetIdentifier}\".`,\n attr,\n didYouMean(targetIdentifier, knownIdentifiers),\n );\n continue;\n }\n const targetName = attr.value.trim();\n if (targetName.length > 0 && !controller.targets.includes(targetName)) {\n const best = nearestName(targetName, controller.targets);\n report(\n node,\n \"unknown-target\",\n \"error\",\n `Unknown target \"${targetName}\" for \"${targetIdentifier}\". Known targets: ${list(controller.targets)}.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, targetName, best),\n );\n }\n const owner = findOwner(node, targetIdentifier);\n if (owner) {\n if (targetName.length > 0) {\n recordPresence(owner, targetIdentifier, targetName);\n recordTargetNode(owner, targetIdentifier, targetName, node);\n }\n } else if (!inDeclaredFragment(node, targetIdentifier)) {\n report(\n node,\n \"orphan-target\",\n \"error\",\n `Target \"${attr.name}\" has no enclosing controller \"${targetIdentifier}\".`,\n attr,\n );\n }\n continue;\n }\n\n // --- value attribute: data-{identifier}-{value}-value ----------------\n if (isStimeoDataAttr(attr.name) && attr.name.endsWith(\"-value\")) {\n const parsed = parseValueAttr(attr.name, knownIdentifiers);\n if (parsed) {\n if (parsed.identifier === null) {\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Value attribute \"${attr.name}\" references unknown Stimeo controller.`,\n attr,\n );\n } else {\n const controller = known[parsed.identifier];\n const valid =\n controller?.values.some((v) => dasherize(v) === parsed.valueToken) ?? false;\n if (!valid) {\n report(\n node,\n \"unknown-value\",\n \"error\",\n `Unknown value \"${parsed.valueToken}\" for \"${parsed.identifier}\". Known values: ${list((controller?.values ?? []).map(dasherize))}.`,\n attr,\n didYouMean(parsed.valueToken, (controller?.values ?? []).map(dasherize)),\n );\n }\n }\n continue;\n }\n }\n\n // --- data-action descriptors: controller + method --------------------\n if (attr.name === \"data-action\") {\n for (const { identifier, method } of actionDescriptors(attr.value)) {\n const controller = known[identifier];\n if (!controller) {\n const best = nearestName(identifier, knownIdentifiers);\n report(\n node,\n \"unknown-action-controller\",\n \"error\",\n `Action references unknown Stimeo controller \"${identifier}\".`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, identifier, best),\n );\n } else if (method.length > 0 && !controller.actions.includes(method)) {\n const best = nearestName(method, controller.actions);\n report(\n node,\n \"unknown-action-method\",\n \"error\",\n `Unknown action \"${method}\" for \"${identifier}\". Known actions: ${list(controller.actions)}.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, method, best),\n );\n }\n }\n }\n }\n });\n\n // --- Stage 2: required targets per scope ---------------------------------\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n const present = presence.get(node)?.get(identifier) ?? new Set<string>();\n for (const required of controller.requiredTargets) {\n if (!present.has(required)) {\n report(\n node,\n \"missing-required-target\",\n \"error\",\n `\"${identifier}\" is missing required target \"${required}\".`,\n node,\n );\n }\n }\n }\n\n // --- Stage 3: accessibility (ARIA) per scope -----------------------------\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const req of controller.a11y) {\n // The root scope (\"\") is the controller element; otherwise the target's\n // own element(s). Targets that are absent are stage 2's concern, not ours\n // — we only judge accessibility of markup that is actually present.\n const elements =\n req.target === \"\"\n ? [node]\n : (targetNodes.get(node)?.get(identifier)?.get(req.target) ?? []);\n for (const el of elements) {\n checkA11y(report, el, identifier, req);\n }\n }\n }\n\n // --- Stage 3: keyboard prerequisites per scope ---------------------------\n // Declared targets whose contract makes the author responsible for\n // focusability must be natively focusable or carry tabindex/contenteditable.\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const req of controller.keyboard) {\n const reach = req.reach ?? \"tab\";\n const elements = targetNodes.get(node)?.get(identifier)?.get(req.target) ?? [];\n for (const el of elements) {\n if (!isFocusable(el, reach)) {\n const problem =\n reach === \"tab\"\n ? 'not in the Tab order (needs a native control or tabindex=\"0\")'\n : \"not focusable (needs a native control or tabindex)\";\n report(\n el,\n \"keyboard-inaccessible\",\n \"error\",\n `The \"${req.target}\" target of \"${identifier}\" is ${problem}.`,\n el,\n req.suggestion,\n );\n }\n }\n }\n }\n\n // --- Stage 3: author-futile (controller-managed) attributes --------------\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const rule of controller.managedAria) {\n const elements =\n rule.target === \"\"\n ? [node]\n : (targetNodes.get(node)?.get(identifier)?.get(rule.target) ?? []);\n const where = rule.target === \"\" ? \"scope element\" : `\"${rule.target}\" target`;\n for (const el of elements) {\n for (const name of rule.attrs) {\n const attr = el.attrs.find((a) => a.name === name);\n if (!attr) continue;\n report(\n el,\n \"managed-aria\",\n \"warning\",\n `${name} on the ${where} of \"${identifier}\" is managed by the controller at runtime.`,\n attr,\n rule.suggestion,\n );\n }\n }\n }\n }\n\n // --- Stage 3: cross-controller composition values ------------------------\n // Value-alignment contracts between a host controller and a co-located\n // companion (e.g. sortable's sort axis vs roving's orientation). Both sides\n // are judged by their *effective* value — the authored attribute, or the\n // rule's declared default when absent — because these contracts exist\n // precisely where the companion's default does not match the host's. An\n // ERB-generated value on either side makes the rule undecidable, so it is\n // skipped rather than guessed at.\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const rule of controller.compositions) {\n const targeted = targetNodes.get(node)?.get(identifier)?.get(rule.target);\n // An absent optional container target falls back to the scope element\n // when the rule says the runtime does the same (e.g. sortable's `list`).\n const elements =\n rule.target === \"\" ? [node] : (targeted ?? (rule.fallbackToScope ? [node] : []));\n const where = rule.target === \"\" || !targeted ? \"scope element\" : `\"${rule.target}\" target`;\n const when = rule.when;\n if (when) {\n const hostAttr = node.attrs.find(\n (a) => a.name === `data-${identifier}-${dasherize(when.value)}-value`,\n );\n if (hostAttr && isDynamicValue(hostAttr)) continue;\n const hostEffective = hostAttr ? hostAttr.value.trim() : when.default;\n if (!when.equals.includes(hostEffective)) continue;\n }\n const hostContext = when ? ` (${when.value} ${list(when.equals)})` : \"\";\n for (const el of elements) {\n const declared = el.attrs.find((a) => a.name === \"data-controller\");\n if (!declared || !controllerIdentifiers(declared.value).includes(rule.coController)) {\n continue;\n }\n const coAttrName = `data-${rule.coController}-${dasherize(rule.require.value)}-value`;\n const coAttr = el.attrs.find((a) => a.name === coAttrName);\n if (coAttr && isDynamicValue(coAttr)) continue;\n const effective = coAttr ? coAttr.value.trim() : rule.require.default;\n if (rule.require.oneOf.includes(effective)) continue;\n const [canonical] = rule.require.oneOf;\n if (!coAttr) {\n report(\n el,\n \"composition-mismatch\",\n \"error\",\n `\"${identifier}\"${hostContext} requires the co-located \"${rule.coController}\" on its ${where} to set ${coAttrName} to ${list(rule.require.oneOf)} (its default is \"${rule.require.default}\").`,\n el,\n rule.suggestion,\n );\n } else {\n report(\n el,\n \"composition-mismatch\",\n \"error\",\n `${coAttrName}=\"${coAttr.value}\" on the ${where} of \"${identifier}\"${hostContext} must be ${list(rule.require.oneOf)}.`,\n coAttr,\n rule.suggestion,\n canonical !== undefined\n ? valueFix(coAttr, canonical, `Set ${coAttrName} to \"${canonical}\"`)\n : undefined,\n );\n }\n }\n }\n }\n\n // --- Stage 3: ARIA idref resolution --------------------------------------\n // Scope/target elements are where the rules above push authors to write\n // reference attributes; a token that resolves to no id in the same file is\n // (at best) split across partials and (at worst) a typo that silently\n // empties an accessible name. Warning severity: only this file is visible.\n const ids = new Set<string>();\n walk(tree, (node) => {\n const id = node.attrs.find((a) => a.name === \"id\");\n if (!id || isDynamicValue(id)) return;\n const value = id.value.trim();\n if (value.length > 0 && !/\\s/.test(value)) ids.add(value);\n });\n\n const anchored = new Set<ElementNode>(scopes.map((scope) => scope.node));\n for (const byIdentifier of targetNodes.values()) {\n for (const byName of byIdentifier.values()) {\n for (const els of byName.values()) {\n for (const el of els) anchored.add(el);\n }\n }\n }\n for (const el of anchored) {\n for (const attr of el.attrs) {\n if (!IDREF_ATTRS.has(attr.name) || isDynamicValue(attr)) continue;\n for (const token of attr.value.split(/\\s+/).filter((t) => t.length > 0)) {\n if (!ids.has(token)) {\n const best = nearestName(token, [...ids]);\n report(\n el,\n \"unresolved-idref\",\n \"warning\",\n `${attr.name} references id \"${token}\", but no element in this file declares it.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, token, best),\n );\n }\n }\n }\n }\n\n diagnostics.sort((a, b) => a.line - b.line || a.column - b.column);\n return diagnostics;\n}\n\n/**\n * Where a diagnostic is anchored in the source: an attribute (position of the\n * attribute name) or an element (position of the tag's `<`). Knowing which of\n * the two it is lets {@link push} derive the anchored token's length.\n */\ntype Anchor = ParsedAttr | ElementNode;\n\n/** Suppression-aware diagnostic sink bound to a source's ignore declarations. */\ntype Reporter = (\n owner: ElementNode,\n code: DiagnosticCode,\n severity: DiagnosticSeverity,\n message: string,\n at: Anchor,\n suggestion?: string,\n fix?: DiagnosticFix,\n) => void;\n\n/**\n * Checks one accessibility requirement against a present element. The base\n * `attrs`/`values` pair and each `or` alternative are alternatives (OR): the\n * requirement is met when at least one candidate attribute is present.\n *\n * Value checking is resolved **per attribute name** by unioning the allowed\n * values across every group that lists that name — so a value valid in *any*\n * of its groups is accepted (a group without `values` accepts anything). This\n * matters when the same attribute appears in more than one group: a value\n * that is valid in one group must not be flagged just because another group\n * lists a different set. Distinct attributes still stand alone, so an authored\n * `aria-live=\"off\"` is flagged even next to a valid `role=\"status\"`.\n */\nfunction checkA11y(\n report: Reporter,\n el: ElementNode,\n identifier: string,\n req: A11yRequirement,\n): void {\n const groups: readonly A11yAlternative[] = [\n { attrs: req.attrs, values: req.values },\n ...(req.or ?? []),\n ];\n const where = req.target === \"\" ? \"scope element\" : `\"${req.target}\" target`;\n\n // Per attribute name: the union of allowed values across the groups that\n // list it (`anyValue` when some group leaves the value unconstrained).\n const allowedByAttr = new Map<string, { anyValue: boolean; values: Set<string> }>();\n for (const group of groups) {\n for (const name of group.attrs) {\n let entry = allowedByAttr.get(name);\n if (!entry) {\n entry = { anyValue: false, values: new Set() };\n allowedByAttr.set(name, entry);\n }\n if (!group.values) entry.anyValue = true;\n else for (const value of group.values) entry.values.add(value);\n }\n }\n\n const invalid: Array<{ attr: ParsedAttr; values: readonly string[] }> = [];\n let anyPresent = false;\n for (const [name, allowed] of allowedByAttr) {\n const attr = el.attrs.find((a) => a.name === name);\n if (!attr) continue;\n anyPresent = true;\n if (!allowed.anyValue && !allowed.values.has(attr.value.trim())) {\n invalid.push({ attr, values: [...allowed.values] });\n }\n }\n\n if (!anyPresent) {\n report(\n el,\n \"missing-aria\",\n \"error\",\n `\"${identifier}\" requires ${describeAttrs([...allowedByAttr.keys()])} on its ${where}.`,\n el,\n req.suggestion,\n );\n return;\n }\n for (const { attr, values } of invalid) {\n // The attribute exists but holds a wrong value, so the rule's \"Add …\"\n // suggestion would mislead — point at the value fix instead. When exactly\n // one value is allowed the correction is unambiguous, so emit it as a\n // machine fix too; multi-valued rules stay a human decision.\n const [only] = values;\n report(\n el,\n \"invalid-aria-value\",\n \"error\",\n `${attr.name}=\"${attr.value}\" is not valid on the ${where} of \"${identifier}\". Expected ${list(values)}.`,\n attr,\n `Set ${attr.name} to ${list(values)}.`,\n values.length === 1 && only !== undefined\n ? valueFix(attr, only, `Set ${attr.name} to \"${only}\"`)\n : undefined,\n );\n }\n}\n\n/** Tags focusable without an authored `tabindex` (input handled separately). */\nconst NATIVE_FOCUSABLE_TAGS = new Set([\"button\", \"select\", \"textarea\", \"summary\"]);\n\n/**\n * Whether the tag is natively focusable **as authored**. `input` is focusable\n * *unless* `type=\"hidden\"` (never rendered, never focusable); `a`/`area` are\n * focusable only with an `href`. Deliberately does **not** consider `disabled`,\n * `hidden`, or `inert`: those are usually intentional states, and — crucially —\n * this library's roving contracts keep items inside an ancestor-`hidden`\n * container until opened (a closed `<ul role=\"menu\" hidden>`), so treating them\n * as non-focusable would false-positive on every correct menu.\n */\nfunction isNativelyFocusable(el: ElementNode): boolean {\n if (NATIVE_FOCUSABLE_TAGS.has(el.tag)) return true;\n if (el.tag === \"input\") {\n const type = (el.attrs.find((a) => a.name === \"type\")?.value ?? \"\").trim().toLowerCase();\n return type !== \"hidden\";\n }\n if (el.tag === \"a\" || el.tag === \"area\") return el.attrs.some((a) => a.name === \"href\");\n return false;\n}\n\n/** Parsed integer `tabindex`, or `null` when absent or not a valid integer. */\nfunction tabindexValue(el: ElementNode): number | null {\n const attr = el.attrs.find((a) => a.name === \"tabindex\");\n if (!attr) return null;\n const parsed = Number.parseInt(attr.value.trim(), 10);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\n/**\n * Static focusability floor for the keyboard-prerequisite pass, per the rule's\n * {@link KeyboardRequirement.reach}:\n *\n * - `\"tab\"`: the element must be in the Tab order — natively focusable /\n * `contenteditable` with no `tabindex`, or `tabindex >= 0`. A `tabindex=\"-1\"`\n * (or a present-but-invalid value) fails, catching the \"removed from Tab\n * order\" bug a presence-only check would miss.\n * - `\"focus\"`: the controller focuses it programmatically, so any valid\n * `tabindex` (including the roving `-1`), a natively focusable element, or\n * `contenteditable` suffices.\n *\n * Presence-only otherwise — the set-level roving invariant is runtime state.\n */\nfunction isFocusable(el: ElementNode, reach: \"tab\" | \"focus\"): boolean {\n const hasTabindex = el.attrs.some((a) => a.name === \"tabindex\");\n if (hasTabindex) {\n const value = tabindexValue(el);\n if (value === null) return false; // present but invalid → not reliably focusable\n return reach === \"tab\" ? value >= 0 : true;\n }\n return isNativelyFocusable(el) || isContentEditable(el);\n}\n\n/**\n * Whether `contenteditable` makes the element focusable. Bare `contenteditable`\n * / `=\"true\"` / `=\"plaintext-only\"` are editable (focusable); only the explicit\n * `=\"false\"` opts out, so it must not count as focusable.\n */\nfunction isContentEditable(el: ElementNode): boolean {\n const attr = el.attrs.find((a) => a.name === \"contenteditable\");\n return attr !== undefined && attr.value.trim().toLowerCase() !== \"false\";\n}\n\n/**\n * ARIA attributes whose value is an idref (list); the idref-resolution pass\n * checks each token against the ids declared in the same file.\n */\nconst IDREF_ATTRS = new Set([\n \"aria-activedescendant\",\n \"aria-controls\",\n \"aria-describedby\",\n \"aria-details\",\n \"aria-errormessage\",\n \"aria-flowto\",\n \"aria-labelledby\",\n \"aria-owns\",\n]);\n\n/**\n * Opts an element (and its subtree) out of diagnostics: an empty value\n * suppresses everything, a whitespace-separated {@link DiagnosticCode} list\n * suppresses exactly those codes. The escape hatch for the rare markup the\n * static rules cannot see well enough (a reference resolved in another\n * partial, an intentionally exotic composition) — each use is greppable and\n * reviewable. Single-dash namespace like {@link FRAGMENT_ATTR}, so it can\n * never collide with a controller's own attribute namespace.\n */\nconst IGNORE_ATTR = \"data-stimeo-ignore\";\n\n/** Climbs the ancestor chain (including `node`) for the nearest owning scope. */\nfunction findOwner(node: ElementNode, identifier: string): ElementNode | null {\n let current: ElementNode | null = node;\n while (current && current.tag !== \"#root\") {\n const dataController = current.attrs.find((a) => a.name === \"data-controller\");\n if (dataController && controllerIdentifiers(dataController.value).includes(identifier)) {\n return current;\n }\n current = current.parent;\n }\n return null;\n}\n\n/**\n * Declares a server-rendered **fragment**: markup a controller fetches and\n * appends at runtime inside its own scope (a Turbo Stream template, an\n * incremental page of `stimeo--feed` articles). Its value is the runtime host —\n * whitespace-separated `stimeo--*` identifiers. Targets inside the declaration\n * are exempt from `orphan-target` for exactly those identifiers; every name is\n * still spell-checked against the manifest, including the declaration itself.\n * Deliberately single-dash (`data-stimeo-`, not `data-stimeo--`) so it can never\n * collide with a controller's own `data-stimeo--<id>-*` attribute namespace.\n */\nconst FRAGMENT_ATTR = \"data-stimeo-fragment\";\n\n/** Whether `node` (or an ancestor) declares itself a fragment of `identifier`. */\nfunction inDeclaredFragment(node: ElementNode, identifier: string): boolean {\n let current: ElementNode | null = node;\n while (current && current.tag !== \"#root\") {\n const declared = current.attrs.find((a) => a.name === FRAGMENT_ATTR);\n if (declared?.value.split(/\\s+/).includes(identifier)) return true;\n current = current.parent;\n }\n return false;\n}\n\n/**\n * Length of the token an anchor points at: the attribute name, or the opening\n * `<tag` (the `<` plus the tag name) for element anchors.\n */\nfunction anchorLength(at: Anchor): number {\n return \"name\" in at ? at.name.length : at.tag.length + 1;\n}\n\n/** Appends a diagnostic positioned at the given source location. */\nfunction push(\n out: Diagnostic[],\n code: DiagnosticCode,\n severity: DiagnosticSeverity,\n message: string,\n at: Anchor,\n suggestion?: string,\n fix?: DiagnosticFix,\n): void {\n out.push({\n code,\n severity,\n message,\n line: at.line,\n column: at.column,\n length: anchorLength(at),\n suggestion,\n fix,\n });\n}\n\n/**\n * Machine fix replacing one occurrence of `token` inside the attribute's\n * value with `replacement`. Returns undefined when there is no replacement,\n * the attribute is boolean (no value offsets), or the token cannot be located\n * verbatim. Uses the first occurrence — a value repeating the same broken\n * token is pathological enough that fixing the first is still the right edit.\n */\nfunction tokenFix(\n attr: ParsedAttr,\n token: string,\n replacement: string | undefined,\n): DiagnosticFix | undefined {\n if (replacement === undefined || attr.valueStart === undefined || token.length === 0) {\n return undefined;\n }\n const index = attr.value.indexOf(token);\n if (index < 0) return undefined;\n const start = attr.valueStart + index;\n return {\n start,\n end: start + token.length,\n text: replacement,\n title: `Replace with \"${replacement}\"`,\n };\n}\n\n/** Machine fix replacing the attribute's entire value. */\nfunction valueFix(attr: ParsedAttr, replacement: string, title: string): DiagnosticFix | undefined {\n if (attr.valueStart === undefined || attr.valueEnd === undefined) return undefined;\n return { start: attr.valueStart, end: attr.valueEnd, text: replacement, title };\n}\n\n/** Formats a name list for human-readable messages. */\nfunction list(names: readonly string[]): string {\n return names.length > 0 ? names.map((n) => `\"${n}\"`).join(\", \") : \"(none)\";\n}\n\n/** Describes a set of \"any of\" attributes, e.g. `aria-labelledby or aria-label`. */\nfunction describeAttrs(attrs: readonly string[]): string {\n return attrs.length === 1 ? (attrs[0] as string) : attrs.join(\" or \");\n}\n\n/**\n * Stage-4 typo candidate: the nearest known name when it is close enough to\n * be a plausible misspelling, else undefined. The threshold scales with name\n * length but is capped, so unrelated names never produce a misleading match.\n * Feeds both the human suggestion ({@link didYouMean}) and the machine fix.\n */\nfunction nearestName(name: string, candidates: readonly string[]): string | undefined {\n if (name.length === 0) return undefined;\n let best: string | undefined;\n let bestDistance = Number.POSITIVE_INFINITY;\n for (const candidate of candidates) {\n const distance = levenshtein(name, candidate);\n if (distance < bestDistance) {\n bestDistance = distance;\n best = candidate;\n }\n }\n const threshold = Math.min(3, Math.floor(name.length / 2) + 1);\n return best !== undefined && bestDistance <= threshold ? best : undefined;\n}\n\n/** Formats a {@link nearestName} candidate as the human-readable suggestion. */\nfunction asDidYouMean(best: string | undefined): string | undefined {\n return best === undefined ? undefined : `Did you mean \"${best}\"?`;\n}\n\n/**\n * Stage-4 typo suggestion: `Did you mean \"x\"?`, or undefined when nothing is\n * close. Exported for the MCP server's `stimeo_controller` unknown-id hint.\n */\nexport function didYouMean(name: string, candidates: readonly string[]): string | undefined {\n return asDidYouMean(nearestName(name, candidates));\n}\n\n/** Classic dynamic-programming Levenshtein edit distance. */\nfunction levenshtein(a: string, b: string): number {\n const rows = a.length;\n const cols = b.length;\n if (rows === 0) return cols;\n if (cols === 0) return rows;\n let prev = Array.from({ length: cols + 1 }, (_, j) => j);\n for (let i = 1; i <= rows; i++) {\n const curr = [i];\n for (let j = 1; j <= cols; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n (curr[j - 1] as number) + 1,\n (prev[j] as number) + 1,\n (prev[j - 1] as number) + cost,\n );\n }\n prev = curr;\n }\n return prev[cols] as number;\n}\n","import { checkSource } from \"./check\";\nimport type { Manifest } from \"./types\";\n\n/**\n * Bundled example index for the MCP server (`stimeo_example` tool and\n * `stimeo://examples/*` resources).\n *\n * The examples are the official catalog's demo sidecars — the exact markup\n * shown verbatim in each demo's code tab and copy-pasted by users, so they\n * are the closest thing the project has to \"verified reference markup\".\n * `scripts/postbuild.ts` walks them at build time (`scripts/demo_sources.ts`\n * resolves the supply: the playground catalog in the dev monorepo,\n * `examples/` in the public mirror) and serializes the result of\n * {@link buildExamplesIndex} into `dist/inspector/examples.json`, next to\n * `manifest.json`.\n *\n * {@link buildExamplesIndex} is pure so the mapping and the verification gate\n * are unit-tested directly; the filesystem walk stays in the build scripts.\n */\n\n/** Format version of `examples.json` (bumped on breaking shape changes). */\nexport const EXAMPLES_SCHEMA_VERSION = 1;\n\n/** One bundled example: the demo markup shown verbatim in the catalog. */\nexport interface ExampleEntry {\n /**\n * Repo-relative provenance: `playground/.../demos/menu/_demo.html.erb` in\n * the dev monorepo, `examples/menu/_demo.html.erb` in the public mirror.\n */\n readonly file: string;\n /** The HTML/ERB source. */\n readonly source: string;\n}\n\n/** The bundled `examples.json`: verified demo markup keyed by controller id. */\nexport interface ExamplesIndex {\n readonly schemaVersion: number;\n /** Keyed by controller identifier, e.g. `stimeo--menu`. Keys are sorted. */\n readonly examples: Readonly<Record<string, ExampleEntry>>;\n}\n\n/** One demo sidecar as discovered on disk by the build script. */\nexport interface DemoSource {\n /** Demo directory basename (snake_case), e.g. `inline_combobox`. */\n readonly dir: string;\n /** Repo-relative path of the `_demo.html.erb` file. */\n readonly file: string;\n /** The file's contents. */\n readonly source: string;\n}\n\n/**\n * Maps a demo directory basename to its controller identifier. Demo dirs use\n * snake_case (`inline_combobox`); controller identifiers are the `stimeo--`\n * prefix plus the kebab-case name (`stimeo--inline-combobox`). The demos tree\n * and the manifest are 1:1 today; {@link buildExamplesIndex} fails the build\n * when either side drifts.\n */\nexport function demoDirToControllerId(dir: string): string {\n return `stimeo--${dir.replaceAll(\"_\", \"-\")}`;\n}\n\n/**\n * Controllers deliberately shipping without a catalog demo *yet*, exempted\n * from the bijection gate below. Currently empty — the server-bound set\n * (typing-indicator / presence / live-counter) and `stimeo--optimistic`\n * gained their demos together with the playground's Action Cable\n * infrastructure. The gate still fails loudly when an entry here gains a\n * demo (stale allowlist) so an exemption cannot outlive its reason.\n */\nexport const PENDING_DEMO_CONTROLLERS: ReadonlySet<string> = new Set([]);\n\n/**\n * Builds the bundled example index from the discovered demo sidecars,\n * enforcing two invariants so \"verified example\" stays true:\n *\n * 1. **Bijection with the manifest.** Every demo dir must map to a known\n * controller and every controller must have a demo — a mismatch on either\n * side means the catalog and the library drifted, and the build must fail\n * loudly rather than silently ship a hole. The only exception is the\n * explicit `pendingDemos` allowlist ({@link PENDING_DEMO_CONTROLLERS}):\n * a documented \"demo not built yet\" deferral, kept honest by the reverse\n * check (an allowlisted controller acquiring a demo fails the build until\n * the stale entry is removed).\n * 2. **Check-clean.** Every example must pass {@link checkSource} with no\n * error-severity diagnostics against the same manifest it ships with.\n *\n * @throws Error listing every violation when an invariant is broken.\n */\nexport function buildExamplesIndex(\n demos: readonly DemoSource[],\n manifest: Manifest,\n pendingDemos: ReadonlySet<string> = PENDING_DEMO_CONTROLLERS,\n): ExamplesIndex {\n const problems: string[] = [];\n const byId = new Map<string, DemoSource>();\n for (const demo of demos) {\n const id = demoDirToControllerId(demo.dir);\n if (!Object.hasOwn(manifest.controllers, id)) {\n problems.push(`demo \"${demo.dir}\" maps to unknown controller \"${id}\"`);\n continue;\n }\n if (byId.has(id)) {\n problems.push(`controller \"${id}\" has more than one demo source`);\n continue;\n }\n byId.set(id, demo);\n }\n for (const id of Object.keys(manifest.controllers)) {\n if (byId.has(id) || pendingDemos.has(id)) continue;\n problems.push(`controller \"${id}\" has no demo example`);\n }\n for (const id of pendingDemos) {\n if (byId.has(id)) {\n problems.push(\n `controller \"${id}\" is allowlisted as pending but now has a demo — ` +\n \"remove it from PENDING_DEMO_CONTROLLERS\",\n );\n }\n }\n for (const [id, demo] of byId) {\n const errors = checkSource(demo.source, manifest).filter((d) => d.severity === \"error\");\n for (const d of errors) {\n problems.push(`example for \"${id}\" fails check: ${d.line}:${d.column} ${d.message}`);\n }\n }\n if (problems.length > 0) {\n throw new Error(`examples index build failed:\\n - ${problems.join(\"\\n - \")}`);\n }\n // Null-prototype dictionary, mirroring runCatalogTool: ids derive from\n // directory names, and a hostile \"__proto__\" would otherwise rewrite the\n // dictionary's prototype instead of storing the entry.\n const examples: Record<string, ExampleEntry> = Object.create(null);\n for (const id of [...byId.keys()].sort()) {\n const demo = byId.get(id);\n if (!demo) continue;\n examples[id] = { file: demo.file, source: demo.source };\n }\n return { schemaVersion: EXAMPLES_SCHEMA_VERSION, examples };\n}\n","import { extname } from \"node:path\";\n\n/**\n * Single source of truth for which files the Inspector checks. Shared by the\n * CLI's directory walk and the VS Code extension's document filter so a file\n * never gets diagnostics in one surface and a silent pass in the other.\n */\n\n/** Final extensions (lowercased) the Inspector understands. `.html.erb` ends with `.erb`. */\nconst CHECKABLE_FILE_EXTENSIONS = new Set([\".erb\", \".html\", \".htm\"]);\n\n/**\n * Whether the path names a checkable HTML/ERB file. Matches on the *final*\n * extension only (`extname`), case-insensitively — case-only variants like\n * `legacy.HTM` are the same file on the case-insensitive filesystems most\n * Rails apps are edited on (macOS/Windows), so they must not slip past CI\n * while the editor flags them.\n */\nexport function isCheckableFile(path: string): boolean {\n return CHECKABLE_FILE_EXTENSIONS.has(extname(path).toLowerCase());\n}\n","import { readFileSync } from \"node:fs\";\nimport type { Manifest } from \"./types\";\n\n/**\n * Loading and shape-validation of `manifest.json` files, shared by every\n * consumer that reads a manifest from disk: the CLI (the copy bundled next to\n * `cli_bin.js`), the VS Code extension (a workspace's installed copy or its\n * bundled snapshot), and any future server (MCP) doing the same. Keeping the\n * guard in one place means a corrupt or cross-version manifest degrades the\n * same way everywhere instead of crashing one surface and passing another.\n */\n\n/** Array-typed fields the schema-v5 engine iterates on every controller entry. */\nconst CONTROLLER_ARRAY_FIELDS = [\n \"targets\",\n \"values\",\n \"actions\",\n \"events\",\n \"requiredTargets\",\n \"a11y\",\n \"keyboard\",\n \"managedAria\",\n \"compositions\",\n] as const;\n\n/**\n * Structural guard for a parsed manifest. A reader bundles the engine of one\n * schema version but may load a manifest written by another (e.g. an app\n * installing a package whose manifest predates `keyboard`/`managedAria`), and\n * the engine iterates those arrays unconditionally — an unvalidated manifest\n * would crash every check instead of failing cleanly. Shape-based rather than\n * a strict `schemaVersion` equality so additive future versions keep working.\n */\nexport function isCompatibleManifest(value: unknown): value is Manifest {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n if (typeof record.schemaVersion !== \"number\" || typeof record.packageVersion !== \"string\") {\n return false;\n }\n const controllers = record.controllers;\n if (typeof controllers !== \"object\" || controllers === null || Array.isArray(controllers)) {\n return false;\n }\n for (const entry of Object.values(controllers as Record<string, unknown>)) {\n if (typeof entry !== \"object\" || entry === null) return false;\n for (const field of CONTROLLER_ARRAY_FIELDS) {\n if (!Array.isArray((entry as Record<string, unknown>)[field])) return false;\n }\n }\n return true;\n}\n\n/**\n * Reads and parses one manifest file; throws on missing/corrupt files and on\n * manifests whose shape the bundled engine cannot consume.\n */\nexport function readManifestFile(path: string): Manifest {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n if (!isCompatibleManifest(parsed)) {\n throw new Error(`Incompatible or malformed manifest: ${path}`);\n }\n return parsed;\n}\n","import { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\nimport { checkSource } from \"./check\";\nimport type { ExamplesIndex } from \"./examples\";\nimport { EXAMPLES_SCHEMA_VERSION } from \"./examples\";\nimport { isCheckableFile } from \"./files\";\nimport { readManifestFile } from \"./manifest_io\";\nimport type { CheckReport, ControllerManifest, Diagnostic, FileReport, Manifest } from \"./types\";\n\n/**\n * `stimeo check <path...>` / `stimeo catalog` — static checker and catalog\n * for `stimeo--*` markup.\n *\n * This is the executable entry point bundled as the `stimeo` npm bin. It is a\n * thin shell around {@link checkSource} and the bundled manifest: discover\n * files, run the engine, format the report, and set the exit code. All checking\n * logic lives in the engine so the CLI and the project's own checks use exactly the same\n * code path. Both commands accept `--json` to emit machine-readable output for\n * editor tooling and CI.\n */\n\n/** Resolves one of the JSON artifacts postbuild writes next to this file in `dist/inspector/`. */\nfunction bundledPath(name: string): string {\n return join(dirname(fileURLToPath(import.meta.url)), name);\n}\n\n/**\n * Loads the manifest bundled next to this file (`dist/inspector/manifest.json`),\n * shape-validated so a corrupt build artifact fails loudly here rather than as\n * an engine crash mid-check. Exported for the MCP server (`stimeo mcp`), which\n * loads the same bundled manifest at startup.\n */\nexport function loadManifest(): Manifest {\n return readManifestFile(bundledPath(\"manifest.json\"));\n}\n\n/**\n * Loads the example index bundled next to this file\n * (`dist/inspector/examples.json`), rejecting a format-version mismatch: the\n * index is only ever read by the build it shipped with, so a mismatch means a\n * corrupted or mixed installation and must fail loudly, not misbehave.\n */\nexport function loadExamplesIndex(): ExamplesIndex {\n const index = JSON.parse(readFileSync(bundledPath(\"examples.json\"), \"utf8\")) as ExamplesIndex;\n if (index.schemaVersion !== EXAMPLES_SCHEMA_VERSION) {\n throw new Error(\n `examples.json schema version ${index.schemaVersion} does not match this build ` +\n `(expected ${EXAMPLES_SCHEMA_VERSION}); reinstall or rebuild the package.`,\n );\n }\n return index;\n}\n\n/** Recursively collects checkable files under the given path. */\nfunction collectFiles(target: string, out: string[]): void {\n const stat = statSync(target);\n if (stat.isDirectory()) {\n for (const entry of readdirSync(target)) {\n collectFiles(join(target, entry), out);\n }\n return;\n }\n if (isCheckableFile(target)) out.push(target);\n}\n\n/** Builds a report for a single file. */\nfunction checkFile(file: string, manifest: Manifest): FileReport {\n const source = readFileSync(file, \"utf8\");\n return { file, diagnostics: checkSource(source, manifest) };\n}\n\n/**\n * Formats one diagnostic, e.g. ` 13:5 error message [code]`. A stage-4\n * suggestion, when present, is appended on its own indented `→` line.\n */\nfunction formatDiagnostic(d: Diagnostic): string {\n const where = `${d.line}:${d.column}`.padEnd(7);\n const head = ` ${where} ${d.severity.padEnd(7)} ${d.message} [${d.code}]`;\n return d.suggestion ? `${head}\\n → ${d.suggestion}` : head;\n}\n\n/**\n * Escapes workflow-command *message* data (`%`, CR, LF) per the GitHub Actions\n * toolkit's escaping rules.\n */\nfunction escapeGithubData(value: string): string {\n return value.replaceAll(\"%\", \"%25\").replaceAll(\"\\r\", \"%0D\").replaceAll(\"\\n\", \"%0A\");\n}\n\n/** Escapes a workflow-command *property* value (message rules plus `:`, `,`). */\nfunction escapeGithubProperty(value: string): string {\n return escapeGithubData(value).replaceAll(\":\", \"%3A\").replaceAll(\",\", \"%2C\");\n}\n\n/**\n * Formats one diagnostic as a GitHub Actions workflow command\n * (`::error file=…,line=…,col=…,title=…::message`). Emitting these from any CI\n * step makes the runner render inline annotations on the PR diff — no\n * marketplace action, upload step, or SARIF pipeline required.\n */\nexport function formatGithubAnnotation(file: string, d: Diagnostic): string {\n const properties = [\n `file=${escapeGithubProperty(file)}`,\n `line=${d.line}`,\n `col=${d.column}`,\n `title=${escapeGithubProperty(`Stimeo Inspector [${d.code}]`)}`,\n ].join(\",\");\n const message = d.suggestion ? `${d.message} → ${d.suggestion}` : d.message;\n return `::${d.severity} ${properties}::${escapeGithubData(message)}`;\n}\n\n/**\n * Aggregates per-file reports into the structured {@link CheckReport}, keeping\n * only files that produced diagnostics and tallying severities. Pure (no I/O),\n * so the JSON output contract is unit-tested directly.\n */\nexport function buildCheckReport(\n reports: readonly FileReport[],\n checkedFiles: number,\n): CheckReport {\n let errorCount = 0;\n let warningCount = 0;\n const files: FileReport[] = [];\n for (const report of reports) {\n if (report.diagnostics.length === 0) continue;\n files.push(report);\n for (const d of report.diagnostics) {\n if (d.severity === \"error\") errorCount++;\n else warningCount++;\n }\n }\n return { ok: errorCount === 0, checkedFiles, errorCount, warningCount, files };\n}\n\n/**\n * Controller entries sorted by identifier — the canonical iteration order for\n * catalog-style output. Shared by the CLI summary below and the MCP\n * `stimeo_catalog` tool so both render the manifest in the same order.\n */\nexport function sortedControllerEntries(\n manifest: Manifest,\n): ReadonlyArray<readonly [string, ControllerManifest]> {\n return Object.keys(manifest.controllers)\n .sort()\n .flatMap((id) => {\n const controller = manifest.controllers[id];\n return controller ? [[id, controller] as const] : [];\n });\n}\n\n/**\n * Renders the manifest as a human-readable catalog: one block per controller\n * listing its non-empty target/value/action/event names. `--json` emits the\n * raw manifest instead, for machine consumption.\n */\nexport function catalogSummary(manifest: Manifest): string[] {\n const entries = sortedControllerEntries(manifest);\n const lines = [\n `Stimeo UI catalog — ${entries.length} controller(s) (schema v${manifest.schemaVersion}, package ${manifest.packageVersion})`,\n \"\",\n ];\n for (const [id, c] of entries) {\n lines.push(id);\n if (c.targets.length > 0) lines.push(` targets: ${c.targets.join(\", \")}`);\n if (c.values.length > 0) lines.push(` values: ${c.values.join(\", \")}`);\n if (c.actions.length > 0) lines.push(` actions: ${c.actions.join(\", \")}`);\n if (c.events.length > 0) lines.push(` events: ${c.events.join(\", \")}`);\n }\n return lines;\n}\n\nconst USAGE = `stimeo — static checker and catalog for Stimeo UI markup\n\nUsage:\n stimeo check [--json|--github] <path...>\n Check HTML/ERB files (or directories) for\n unknown or misused stimeo--* controllers,\n targets, values and action methods.\n stimeo catalog [--json] Print the official controller catalog\n (identifiers, targets, values, actions,\n events).\n stimeo mcp Run a Model Context Protocol server over\n stdio, exposing the checker, catalog, and\n verified example markup as read-only tools\n (stimeo_check, stimeo_catalog,\n stimeo_controller, stimeo_example),\n resources, and workflow prompts for AI\n coding agents.\n\n--json makes either command emit machine-readable JSON (for tooling / MCP):\ncheck prints a CheckReport, catalog prints the raw manifest.\n--github prints check results as GitHub Actions workflow commands\n(::error / ::warning), which CI renders as inline PR annotations.\nExit code is 1 when any error is found (warnings never fail the run).`;\n\n/**\n * Runs the CLI.\n *\n * @param argv - Arguments after the node executable and script (`process.argv.slice(2)`).\n * @param write - Output sink (defaults to stdout); injectable for tests.\n * @param load - Manifest loader (defaults to the bundled manifest); injectable for tests.\n * @returns Process exit code (0 = clean, 1 = errors found, 2 = usage error).\n */\nexport function runCli(\n argv: readonly string[],\n write: (line: string) => void = console.log,\n load: () => Manifest = loadManifest,\n): number {\n const [command, ...rest] = argv;\n\n if (command === undefined || command === \"--help\" || command === \"-h\") {\n write(USAGE);\n return command === undefined ? 2 : 0;\n }\n\n const json = rest.includes(\"--json\");\n const github = rest.includes(\"--github\");\n if (json && github) {\n write(`--json and --github are mutually exclusive.\\n\\n${USAGE}`);\n return 2;\n }\n\n if (command === \"catalog\") {\n const manifest = load();\n if (json) {\n write(JSON.stringify(manifest, null, 2));\n } else {\n for (const line of catalogSummary(manifest)) write(line);\n }\n return 0;\n }\n\n if (command !== \"check\") {\n write(`Unknown command \"${command}\".\\n\\n${USAGE}`);\n return 2;\n }\n\n const paths = rest.filter((arg) => !arg.startsWith(\"-\"));\n if (paths.length === 0) {\n write(`No paths given.\\n\\n${USAGE}`);\n return 2;\n }\n\n const files: string[] = [];\n for (const path of paths) {\n try {\n collectFiles(path, files);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n const reason =\n code === \"ENOENT\"\n ? \"no such file or directory\"\n : code === \"EACCES\"\n ? \"permission denied\"\n : ((err as Error).message ?? \"cannot access path\");\n write(`Cannot read path \"${path}\": ${reason}.\\n\\n${USAGE}`);\n return 2;\n }\n }\n\n const manifest = load();\n const cwd = process.cwd();\n const reports: FileReport[] = [];\n for (const file of files.sort()) {\n reports.push({\n file: relative(cwd, file) || file,\n diagnostics: checkFile(file, manifest).diagnostics,\n });\n }\n const summary = buildCheckReport(reports, files.length);\n\n if (json) {\n write(JSON.stringify(summary, null, 2));\n return summary.errorCount > 0 ? 1 : 0;\n }\n\n if (github) {\n for (const report of summary.files) {\n for (const d of report.diagnostics) write(formatGithubAnnotation(report.file, d));\n }\n } else {\n for (const report of summary.files) {\n write(report.file);\n for (const d of report.diagnostics) write(formatDiagnostic(d));\n write(\"\");\n }\n }\n\n const total = summary.errorCount + summary.warningCount;\n if (total === 0) {\n write(`✓ Checked ${summary.checkedFiles} file(s); no problems found.`);\n return 0;\n }\n write(\n `✖ ${total} problem(s) (${summary.errorCount} error(s), ${summary.warningCount} warning(s)).`,\n );\n return summary.errorCount > 0 ? 1 : 0;\n}\n","/**\n * Prompt definitions for the `stimeo mcp` server (`prompts/list` /\n * `prompts/get`).\n *\n * Prompts are user-invokable workflow templates (surfaced as slash commands\n * in Claude Code, for example) that bake in the correct tool sequence —\n * discover via `stimeo_catalog`, pull the contract via `stimeo_controller`,\n * reference `stimeo_example`, and validate with `stimeo_check` before\n * presenting — so the calling model does not have to rediscover the workflow\n * each time. They are static text with argument interpolation; all live data\n * still flows through the tools.\n *\n * Handlers are pure (`(name, args) → messages`) like the tool handlers, so\n * they are unit-tested without a protocol round-trip.\n */\n\n/** One argument accepted by a prompt, as advertised in `prompts/list`. */\nexport interface PromptArgumentDescriptor {\n readonly name: string;\n readonly description: string;\n readonly required: boolean;\n}\n\n/** One entry of the `prompts/list` response. */\nexport interface PromptDescriptor {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly arguments: readonly PromptArgumentDescriptor[];\n}\n\n/** One message of a `prompts/get` result (this server emits text only). */\nexport interface PromptMessage {\n readonly role: \"user\";\n readonly content: { readonly type: \"text\"; readonly text: string };\n}\n\n/** The `prompts/get` result payload. */\nexport interface PromptResult {\n readonly description: string;\n readonly messages: readonly PromptMessage[];\n}\n\n/**\n * Raised when `prompts/get` names an unknown prompt or passes malformed\n * arguments. The server maps this to a JSON-RPC \"Invalid params\" (-32602)\n * protocol error, per the MCP prompts spec.\n */\nexport class InvalidPromptRequestError extends Error {}\n\n/**\n * Narrows unknown `prompts/get` arguments to a string-valued record (the MCP\n * prompts spec allows string values only), treating absence as empty and\n * rejecting keys the prompt does not declare.\n */\nfunction asPromptArgs(args: unknown, allowed: readonly string[]): Record<string, string> {\n if (args === undefined || args === null) return {};\n if (typeof args !== \"object\" || Array.isArray(args)) {\n throw new InvalidPromptRequestError(\"Prompt arguments must be an object.\");\n }\n const record = args as Record<string, unknown>;\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(record)) {\n if (!allowed.includes(key)) {\n throw new InvalidPromptRequestError(`Unknown argument \"${key}\".`);\n }\n if (typeof value !== \"string\") {\n throw new InvalidPromptRequestError(`Argument \"${key}\" must be a string.`);\n }\n result[key] = value;\n }\n return result;\n}\n\n/** Reads a required argument, present and non-empty. */\nfunction requireArg(record: Record<string, string>, key: string): string {\n const value = record[key];\n if (value === undefined || value.trim() === \"\") {\n throw new InvalidPromptRequestError(`Argument \"${key}\" is required.`);\n }\n return value;\n}\n\n/**\n * Reads an optional argument, trimmed; a blank value counts as absent so a\n * whitespace-only slash-command input cannot leak into the prompt text.\n */\nfunction optionalArg(record: Record<string, string>, key: string): string | undefined {\n const value = record[key]?.trim();\n return value ? value : undefined;\n}\n\n/** Builds the `stimeo_build_ui` messages. */\nfunction buildUiPrompt(args: Record<string, string>): PromptResult {\n const request = requireArg(args, \"request\");\n const controller = optionalArg(args, \"controller\");\n const start = controller\n ? `Start from the controller \"${controller}\" (verify it exists with stimeo_controller; ` +\n \"if it does not, fall back to discovery via stimeo_catalog).\"\n : \"Call stimeo_catalog to find the controller(s) that fit the task.\";\n const text =\n \"You are building UI for a Rails app with Stimeo UI, a headless (behavior-only) Stimulus \" +\n \"framework driven by data-* attributes. It ships no CSS; styling is the app's own.\\n\\n\" +\n `Task: ${request}\\n\\n` +\n \"Follow this workflow with the stimeo MCP tools:\\n\" +\n `1. ${start}\\n` +\n \"2. Call stimeo_controller for each chosen controller to get its contract: required \" +\n \"targets, author-supplied ARIA, keyboard prerequisites, and the ARIA it manages at \" +\n \"runtime (never hardcode those managed attributes).\\n\" +\n \"3. Call stimeo_example for each chosen controller and use the verified markup as your \" +\n \"structural reference.\\n\" +\n \"4. Write the markup: keep every data-*, role, and aria-* attribute the contract and \" +\n \"example require; replace demo class attributes with the app's own styling.\\n\" +\n \"5. Call stimeo_check on the markup you wrote and fix every diagnostic (each one carries \" +\n \"a fix suggestion when available). Repeat until ok is true — only then present the \" +\n \"result.\";\n return {\n description: \"Build Stimeo UI markup with the discover → contract → example → check workflow.\",\n messages: [{ role: \"user\", content: { type: \"text\", text } }],\n };\n}\n\n/** Builds the `stimeo_fix_markup` messages. */\nfunction fixMarkupPrompt(args: Record<string, string>): PromptResult {\n const source = requireArg(args, \"source\");\n const filename = optionalArg(args, \"filename\");\n const filenameClause = filename ? ` (filename: \"${filename}\")` : \"\";\n // The source is fenced so its own prose cannot read as workflow steps.\n const text =\n \"You are reviewing existing markup that uses Stimeo UI (stimeo--*) controllers.\\n\\n\" +\n `1. Call stimeo_check with the fenced source below${filenameClause}.\\n` +\n \"2. For each diagnostic, apply its fix suggestion; when a fix needs context, call \" +\n \"stimeo_controller for the affected controller's contract and stimeo_example for verified \" +\n \"reference markup.\\n\" +\n \"3. Re-run stimeo_check on the corrected markup until ok is true.\\n\" +\n \"4. Present the corrected markup and a short list of what changed and why.\\n\\n\" +\n `Source:\\n\\n\\`\\`\\`erb\\n${source}\\n\\`\\`\\``;\n return {\n description: \"Check the given markup and fix every diagnostic until stimeo_check passes.\",\n messages: [{ role: \"user\", content: { type: \"text\", text } }],\n };\n}\n\n/** One prompt: its `prompts/list` descriptor plus its message builder. */\ninterface PromptDefinition {\n readonly descriptor: PromptDescriptor;\n readonly build: (args: Record<string, string>) => PromptResult;\n}\n\n/**\n * The prompts this server serves. Descriptor and builder live side by side so\n * a prompt cannot be advertised without being dispatchable (adding an entry\n * here is the whole registration).\n */\nconst PROMPTS: readonly PromptDefinition[] = [\n {\n descriptor: {\n name: \"stimeo_build_ui\",\n title: \"Build UI with Stimeo UI\",\n description:\n \"Build Rails view markup for a requested UI using Stimeo UI controllers, following the \" +\n \"verified workflow: discover with stimeo_catalog, read the contract with \" +\n \"stimeo_controller, reference stimeo_example, and validate with stimeo_check before \" +\n \"presenting.\",\n arguments: [\n {\n name: \"request\",\n description: 'What to build, e.g. \"a confirmation dialog for deleting a project\".',\n required: true,\n },\n {\n name: \"controller\",\n description:\n 'Optional controller identifier to start from, e.g. \"stimeo--dialog\". ' +\n \"Omit to let the workflow discover one via stimeo_catalog.\",\n required: false,\n },\n ],\n },\n build: buildUiPrompt,\n },\n {\n descriptor: {\n name: \"stimeo_fix_markup\",\n title: \"Check and fix Stimeo UI markup\",\n description:\n \"Check existing HTML/ERB that uses stimeo--* controllers with stimeo_check, fix every \" +\n \"diagnostic using the fix suggestions and the controller contracts, and re-check until \" +\n \"clean.\",\n arguments: [\n {\n name: \"source\",\n description: \"The HTML or ERB source to check and fix.\",\n required: true,\n },\n {\n name: \"filename\",\n description: 'Optional filename for diagnostics, e.g. \"app/views/users/show.html.erb\".',\n required: false,\n },\n ],\n },\n build: fixMarkupPrompt,\n },\n];\n\n/** Prompt descriptors advertised via `prompts/list`. */\nexport const PROMPT_DESCRIPTORS: readonly PromptDescriptor[] = PROMPTS.map(\n (prompt) => prompt.descriptor,\n);\n\n/**\n * Dispatches one `prompts/get` invocation to its builder.\n *\n * @throws InvalidPromptRequestError for unknown prompt names or malformed\n * arguments (mapped to JSON-RPC -32602 by the server).\n */\nexport function getPrompt(name: string, args: unknown): PromptResult {\n const prompt = PROMPTS.find((entry) => entry.descriptor.name === name);\n if (!prompt) {\n throw new InvalidPromptRequestError(`Unknown prompt \"${name}\".`);\n }\n const record = asPromptArgs(\n args,\n prompt.descriptor.arguments.map((argument) => argument.name),\n );\n return prompt.build(record);\n}\n","import { checkSource, didYouMean } from \"../check\";\nimport { buildCheckReport, sortedControllerEntries } from \"../cli\";\nimport type { ExamplesIndex } from \"../examples\";\nimport type { CheckReport, ControllerManifest, Manifest } from \"../types\";\nimport { DIAGNOSTIC_CODES } from \"../types\";\n\n/**\n * Tool definitions and pure handlers for the `stimeo mcp` server.\n *\n * Each MCP tool wraps an existing pure engine function ({@link checkSource},\n * {@link buildCheckReport}, manifest lookups) so the server, the CLI, and the\n * project's own CI gate share exactly the same code path. Each handler takes\n * `args` plus the slice of {@link ToolContext} it needs (the manifest, the\n * example index, or both) and returns a plain JSON-serializable object; the\n * handlers perform no I/O, so they are unit-tested directly without a\n * protocol round-trip.\n *\n * All tools are read-only: `stimeo_check` inspects a source string passed by\n * the client (no filesystem traversal), the others only read the bundled\n * manifest and example index.\n */\n\n/** Names of the tools exposed by the MCP server. */\nexport type ToolName = \"stimeo_check\" | \"stimeo_catalog\" | \"stimeo_controller\" | \"stimeo_example\";\n\n/**\n * Everything the tool dispatcher needs: the reflected manifest plus the\n * bundled example index (both generated at build time next to the CLI).\n */\nexport interface ToolContext {\n readonly manifest: Manifest;\n readonly examples: ExamplesIndex;\n}\n\n/** Minimal JSON Schema subset used to describe tool inputs in `tools/list`. */\nexport interface ToolInputSchema {\n readonly type: \"object\";\n readonly properties: Readonly<\n Record<string, { readonly type: string; readonly description: string }>\n >;\n readonly required?: readonly string[];\n readonly additionalProperties: boolean;\n}\n\n/**\n * MCP tool annotations (protocol 2025-03-26+): machine-readable behavior hints.\n * Every v1 tool is read-only and closed-world (it only consults the bundled\n * manifest and the strings the client sends), so clients can skip destructive-\n * action confirmation UX.\n */\nexport interface ToolAnnotations {\n readonly readOnlyHint: boolean;\n readonly openWorldHint: boolean;\n}\n\n/**\n * JSON Schema for a tool result (`outputSchema` in `tools/list`). Typed as a\n * plain JSON object rather than a full JSON Schema model: the schemas below\n * are hand-written literals, and their conformance to what the handlers\n * actually return is locked by `mcp_tools.test.ts`.\n */\nexport type ToolOutputSchema = Readonly<Record<string, unknown>>;\n\n/** One entry of the `tools/list` response. */\nexport interface ToolDescriptor {\n readonly name: ToolName;\n readonly title: string;\n readonly description: string;\n readonly annotations: ToolAnnotations;\n readonly inputSchema: ToolInputSchema;\n readonly outputSchema: ToolOutputSchema;\n}\n\n/** Shared annotations: every v1 tool is read-only over bundled data. */\nconst READ_ONLY_ANNOTATIONS: ToolAnnotations = { readOnlyHint: true, openWorldHint: false };\n\n/** JSON Schema fragment for a `readonly string[]` field. */\nconst STRING_ARRAY = { type: \"array\", items: { type: \"string\" } } as const;\n\n/** JSON Schema for one diagnostic inside a {@link CheckReport}. */\nconst DIAGNOSTIC_SCHEMA = {\n type: \"object\",\n properties: {\n code: { type: \"string\", enum: DIAGNOSTIC_CODES },\n severity: { type: \"string\", enum: [\"error\", \"warning\"] },\n message: { type: \"string\" },\n line: { type: \"integer\", description: \"1-based line where the problem was detected.\" },\n column: { type: \"integer\", description: \"1-based column where the problem was detected.\" },\n suggestion: { type: \"string\", description: \"Fix suggestion (stage 4), when available.\" },\n },\n required: [\"code\", \"severity\", \"message\", \"line\", \"column\"],\n} as const;\n\n/** JSON Schema for the `stimeo_check` result (mirrors {@link CheckReport}). */\nconst CHECK_REPORT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n description: \"Aggregated check result; same shape as `stimeo check --json`.\",\n properties: {\n ok: { type: \"boolean\", description: \"True when no error-severity diagnostics were found.\" },\n checkedFiles: { type: \"integer\" },\n errorCount: { type: \"integer\" },\n warningCount: { type: \"integer\" },\n files: {\n type: \"array\",\n description: \"Only files that produced at least one diagnostic.\",\n items: {\n type: \"object\",\n properties: {\n file: { type: \"string\" },\n diagnostics: { type: \"array\", items: DIAGNOSTIC_SCHEMA },\n },\n required: [\"file\", \"diagnostics\"],\n },\n },\n },\n required: [\"ok\", \"checkedFiles\", \"errorCount\", \"warningCount\", \"files\"],\n};\n\n/** JSON Schema for the `stimeo_catalog` result (mirrors {@link CatalogResult}). */\nconst CATALOG_RESULT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n properties: {\n schemaVersion: { type: \"integer\" },\n packageVersion: { type: \"string\" },\n controllerCount: { type: \"integer\" },\n controllers: {\n type: \"object\",\n description: 'Keyed by controller identifier, e.g. \"stimeo--menu\".',\n additionalProperties: {\n type: \"object\",\n properties: {\n targets: STRING_ARRAY,\n values: STRING_ARRAY,\n actions: STRING_ARRAY,\n events: STRING_ARRAY,\n },\n required: [\"targets\", \"values\", \"actions\", \"events\"],\n },\n },\n },\n required: [\"schemaVersion\", \"packageVersion\", \"controllerCount\", \"controllers\"],\n};\n\n/** JSON Schema for the `stimeo_example` result (mirrors {@link ExampleResult}). */\nconst EXAMPLE_RESULT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: 'Controller identifier, e.g. \"stimeo--menu\".' },\n file: {\n type: \"string\",\n description: \"Repo-relative provenance of the example (the catalog demo sidecar).\",\n },\n source: { type: \"string\", description: \"The HTML/ERB example source.\" },\n guidance: { type: \"string\", description: \"How to consume the example correctly.\" },\n },\n required: [\"id\", \"file\", \"source\", \"guidance\"],\n};\n\n/** JSON Schema for the `stimeo_controller` result (mirrors {@link ControllerContract}). */\nconst CONTROLLER_CONTRACT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: 'Controller identifier, e.g. \"stimeo--tabs\".' },\n targets: STRING_ARRAY,\n values: STRING_ARRAY,\n actions: STRING_ARRAY,\n events: STRING_ARRAY,\n requiredTargets: {\n ...STRING_ARRAY,\n description: \"Targets that must be present at least once inside the controller scope.\",\n },\n a11y: {\n type: \"array\",\n description: \"Author-supplied ARIA the controller relies on but never sets itself.\",\n items: {\n type: \"object\",\n properties: {\n target: {\n type: \"string\",\n description: 'Target name; \"\" means the data-controller element itself.',\n },\n attrs: { ...STRING_ARRAY, description: \"At least one of these must be present.\" },\n values: { ...STRING_ARRAY, description: \"Allowed values; absent = any value.\" },\n or: {\n type: \"array\",\n description: \"Alternative attribute groups; satisfying any group satisfies the rule.\",\n items: {\n type: \"object\",\n properties: { attrs: STRING_ARRAY, values: STRING_ARRAY },\n required: [\"attrs\"],\n },\n },\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"attrs\", \"suggestion\"],\n },\n },\n keyboard: {\n type: \"array\",\n description: \"Targets whose keyboard focusability the author must provide.\",\n items: {\n type: \"object\",\n properties: {\n target: { type: \"string\" },\n reach: {\n type: \"string\",\n enum: [\"tab\", \"focus\"],\n description: 'How focus arrives; defaults to \"tab\" (steady Tab stop).',\n },\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"suggestion\"],\n },\n },\n managedAria: {\n type: \"array\",\n description: \"ARIA the controller recomputes at runtime; authoring it is a warning.\",\n items: {\n type: \"object\",\n properties: {\n target: { type: \"string\" },\n attrs: STRING_ARRAY,\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"attrs\", \"suggestion\"],\n },\n },\n compositions: {\n type: \"array\",\n description:\n \"Cross-controller value alignments: when the companion controller is co-located on \" +\n \"the named target, its value (authored or default) must be one of the allowed set.\",\n items: {\n type: \"object\",\n properties: {\n target: {\n type: \"string\",\n description: 'Host target hosting the companion; \"\" means the data-controller element.',\n },\n fallbackToScope: {\n type: \"boolean\",\n description: \"Check the scope element when the target is absent.\",\n },\n coController: { type: \"string\", description: \"Companion controller identifier.\" },\n when: {\n type: \"object\",\n description: \"Host-value condition arming the rule; absent means unconditional.\",\n properties: {\n value: { type: \"string\" },\n equals: STRING_ARRAY,\n default: { type: \"string\" },\n },\n required: [\"value\", \"equals\", \"default\"],\n },\n require: {\n type: \"object\",\n description: \"Companion-value requirement (first allowed value is canonical).\",\n properties: {\n value: { type: \"string\" },\n oneOf: STRING_ARRAY,\n default: { type: \"string\" },\n },\n required: [\"value\", \"oneOf\", \"default\"],\n },\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"coController\", \"require\", \"suggestion\"],\n },\n },\n },\n required: [\n \"id\",\n \"targets\",\n \"values\",\n \"actions\",\n \"events\",\n \"requiredTargets\",\n \"a11y\",\n \"keyboard\",\n \"managedAria\",\n \"compositions\",\n ],\n};\n\n/**\n * Raised when `tools/call` arguments fail validation. The server maps this to\n * a JSON-RPC \"Invalid params\" (-32602) protocol error, per the MCP spec's\n * distinction between protocol errors and tool execution errors.\n */\nexport class InvalidToolArgsError extends Error {}\n\n/**\n * Raised when a tool runs but cannot produce a result (e.g. unknown controller\n * id). The server maps this to a tool result with `isError: true`, so the\n * calling model sees the message and can self-correct.\n */\nexport class ToolExecutionError extends Error {}\n\n/** Report filename used by `stimeo_check` when the client does not send one. */\nexport const DEFAULT_CHECK_FILENAME = \"source.erb\";\n\n/** Catalog view of one controller: the reflected `data-*` API surface only. */\nexport interface CatalogController {\n readonly targets: readonly string[];\n readonly values: readonly string[];\n readonly actions: readonly string[];\n readonly events: readonly string[];\n}\n\n/**\n * Result of `stimeo_catalog`: every controller's API surface, without the\n * per-controller contract rules (those come from `stimeo_controller`), keeping\n * the discovery payload small for model consumption.\n */\nexport interface CatalogResult {\n readonly schemaVersion: number;\n readonly packageVersion: string;\n readonly controllerCount: number;\n readonly controllers: Readonly<Record<string, CatalogController>>;\n}\n\n/** Result of `stimeo_controller`: the full manifest entry plus its id. */\nexport interface ControllerContract extends ControllerManifest {\n readonly id: string;\n}\n\n/** Result of `stimeo_example`: one controller's verified example markup. */\nexport interface ExampleResult {\n readonly id: string;\n /** Repo-relative provenance of the example (the catalog demo sidecar). */\n readonly file: string;\n /** The HTML/ERB source. */\n readonly source: string;\n /** How to consume the example correctly ({@link EXAMPLE_GUIDANCE}). */\n readonly guidance: string;\n}\n\n/**\n * Consumption note attached to every `stimeo_example` result. The examples are\n * headless-catalog demos: the `stimeo--*` data attributes are the contract;\n * class attributes are demo styling placeholders the consumer must replace.\n */\nexport const EXAMPLE_GUIDANCE =\n \"Verified example from the official Stimeo UI catalog (it passes stimeo_check against the \" +\n \"bundled manifest). Behavior and accessibility come from the data-* attributes and any \" +\n \"role/aria-* attributes shown; keep those intact. class attributes are demo styling \" +\n \"placeholders — the library ships no CSS, so replace them with your own classes. ERB \" +\n \"helpers/comments illustrate Rails usage and can be adapted.\";\n\n/** Tool descriptors advertised via `tools/list`. */\nexport const TOOL_DESCRIPTORS: readonly ToolDescriptor[] = [\n {\n name: \"stimeo_check\",\n title: \"Check Stimeo UI markup\",\n description:\n \"Statically check HTML or ERB source that uses Stimeo UI (stimeo--*) controllers. \" +\n \"Returns a CheckReport with diagnostics — unknown controllers/targets/values/action \" +\n \"methods, missing required targets, missing or invalid author-supplied ARIA, \" +\n \"keyboard-focusability prerequisites, and misaligned cross-controller composition \" +\n \"values — each with a fix suggestion when available. \" +\n \"Call this on generated markup before finalizing it; ok=true means no errors.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {\n source: {\n type: \"string\",\n description: \"The HTML or ERB source to check.\",\n },\n filename: {\n type: \"string\",\n description:\n 'Optional filename reported in diagnostics (e.g. \"app/views/users/show.html.erb\").',\n },\n },\n required: [\"source\"],\n additionalProperties: false,\n },\n outputSchema: CHECK_REPORT_SCHEMA,\n },\n {\n name: \"stimeo_catalog\",\n title: \"List Stimeo UI controllers\",\n description:\n \"List every Stimeo UI controller with its targets, values, actions, and events. \" +\n \"Use this to discover which stimeo--* controllers exist and the data-* API each \" +\n \"accepts before writing markup.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n outputSchema: CATALOG_RESULT_SCHEMA,\n },\n {\n name: \"stimeo_controller\",\n title: \"Get one controller's usage contract\",\n description:\n \"Fetch the full usage contract of one Stimeo UI controller by identifier \" +\n '(e.g. \"stimeo--tabs\"): targets, values, actions, events, required targets, and the ' +\n \"accessibility contract — author-supplied ARIA requirements, keyboard-focusability \" +\n \"prerequisites, the ARIA attributes the controller manages at runtime (which the \" +\n \"author must NOT hardcode), and cross-controller composition value alignments.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: 'Controller identifier, e.g. \"stimeo--tabs\".',\n },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n outputSchema: CONTROLLER_CONTRACT_SCHEMA,\n },\n {\n name: \"stimeo_example\",\n title: \"Get one controller's verified example markup\",\n description:\n \"Fetch verified example markup for one Stimeo UI controller by identifier \" +\n '(e.g. \"stimeo--menu\"). The example is the official catalog demo — it passes ' +\n \"stimeo_check against the bundled manifest, so use it as the reference for correct \" +\n \"structure, required targets, and author-supplied ARIA. class attributes in it are \" +\n \"demo styling placeholders to replace; the stimeo--* data attributes and role/aria-* \" +\n \"attributes are the contract to keep.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: 'Controller identifier, e.g. \"stimeo--menu\".',\n },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n outputSchema: EXAMPLE_RESULT_SCHEMA,\n },\n];\n\n/**\n * Narrows unknown `tools/call` arguments to a record, treating absence as\n * empty. Unknown keys are rejected so behavior matches the advertised\n * `additionalProperties: false` in every tool's input schema.\n */\nfunction asArgsRecord(args: unknown, allowed: readonly string[]): Record<string, unknown> {\n if (args === undefined || args === null) return {};\n if (typeof args !== \"object\" || Array.isArray(args)) {\n throw new InvalidToolArgsError(\"Tool arguments must be an object.\");\n }\n const record = args as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!allowed.includes(key)) {\n throw new InvalidToolArgsError(`Unknown argument \"${key}\".`);\n }\n }\n return record;\n}\n\n/** Reads a required string property from tool arguments. */\nfunction requireString(record: Record<string, unknown>, key: string): string {\n const value = record[key];\n if (typeof value !== \"string\") {\n throw new InvalidToolArgsError(`Argument \"${key}\" is required and must be a string.`);\n }\n return value;\n}\n\n/** Reads an optional string property from tool arguments. */\nfunction optionalString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n if (value === undefined) return undefined;\n if (typeof value !== \"string\") {\n throw new InvalidToolArgsError(`Argument \"${key}\" must be a string when given.`);\n }\n return value;\n}\n\n/**\n * `stimeo_check`: runs the engine on one in-memory source and aggregates the\n * diagnostics into a {@link CheckReport}, exactly like `stimeo check --json`\n * does for files on disk.\n */\nexport function runCheckTool(manifest: Manifest, args: unknown): CheckReport {\n const record = asArgsRecord(args, [\"source\", \"filename\"]);\n const source = requireString(record, \"source\");\n const filename = optionalString(record, \"filename\") ?? DEFAULT_CHECK_FILENAME;\n return buildCheckReport([{ file: filename, diagnostics: checkSource(source, manifest) }], 1);\n}\n\n/** `stimeo_catalog`: the API surface of every controller, sorted by identifier. */\nexport function runCatalogTool(manifest: Manifest): CatalogResult {\n // Null-prototype dictionary: manifest keys come from parsed JSON, and\n // assigning a hostile \"__proto__\" key onto a plain object would silently\n // rewrite the dictionary's prototype instead of storing the entry.\n const controllers: Record<string, CatalogController> = Object.create(null);\n for (const [id, controller] of sortedControllerEntries(manifest)) {\n controllers[id] = {\n targets: controller.targets,\n values: controller.values,\n actions: controller.actions,\n events: controller.events,\n };\n }\n return {\n schemaVersion: manifest.schemaVersion,\n packageVersion: manifest.packageVersion,\n controllerCount: Object.keys(controllers).length,\n controllers,\n };\n}\n\n/**\n * Prototype-safe dictionary lookup. The manifest and example dictionaries are\n * parsed JSON, so bare bracket access would resolve prototype keys\n * (\"constructor\", \"toString\", \"__proto__\", …) to inherited members and fake a\n * successful lookup for a nonexistent id — a hostile key must read as absent.\n */\nexport function getOwn<T>(dict: Readonly<Record<string, T>>, key: string): T | undefined {\n return Object.hasOwn(dict, key) ? dict[key] : undefined;\n}\n\n/**\n * `stimeo_controller`: one controller's full contract (a11y and keyboard\n * requirements included). Unknown ids produce a tool execution error with a\n * \"did you mean\" hint so the calling model can self-correct.\n */\nexport function runControllerTool(manifest: Manifest, args: unknown): ControllerContract {\n const record = asArgsRecord(args, [\"id\"]);\n const id = requireString(record, \"id\");\n const controller = getOwn(manifest.controllers, id);\n if (!controller) {\n const hint = didYouMean(id, Object.keys(manifest.controllers));\n throw new ToolExecutionError(\n `Unknown controller \"${id}\".${hint ? ` ${hint}` : \"\"} Use stimeo_catalog to list available controllers.`,\n );\n }\n return { id, ...controller };\n}\n\n/**\n * `stimeo_example`: one controller's verified example markup, straight from\n * the bundled catalog-demo index. Unknown ids produce a tool execution error\n * with a \"did you mean\" hint so the calling model can self-correct.\n */\nexport function runExampleTool(examples: ExamplesIndex, args: unknown): ExampleResult {\n const record = asArgsRecord(args, [\"id\"]);\n const id = requireString(record, \"id\");\n const entry = getOwn(examples.examples, id);\n if (!entry) {\n const hint = didYouMean(id, Object.keys(examples.examples));\n throw new ToolExecutionError(\n `No example for controller \"${id}\".${hint ? ` ${hint}` : \"\"} Use stimeo_catalog to list available controllers.`,\n );\n }\n return { id, file: entry.file, source: entry.source, guidance: EXAMPLE_GUIDANCE };\n}\n\n/**\n * Dispatches one `tools/call` invocation to its handler.\n *\n * @throws InvalidToolArgsError for unknown tool names or malformed arguments\n * (protocol error), {@link ToolExecutionError} for failures inside a tool\n * (returned as an `isError` tool result).\n */\nexport function callTool(context: ToolContext, name: string, args: unknown): unknown {\n switch (name) {\n case \"stimeo_check\":\n return runCheckTool(context.manifest, args);\n case \"stimeo_catalog\":\n asArgsRecord(args, []);\n return runCatalogTool(context.manifest);\n case \"stimeo_controller\":\n return runControllerTool(context.manifest, args);\n case \"stimeo_example\":\n return runExampleTool(context.examples, args);\n default:\n throw new InvalidToolArgsError(`Unknown tool \"${name}\".`);\n }\n}\n","import { createInterface } from \"node:readline\";\nimport type { Readable } from \"node:stream\";\nimport { getPrompt, InvalidPromptRequestError, PROMPT_DESCRIPTORS } from \"./prompts\";\nimport type { ToolContext } from \"./tools\";\nimport {\n callTool,\n getOwn,\n InvalidToolArgsError,\n TOOL_DESCRIPTORS,\n ToolExecutionError,\n} from \"./tools\";\n\n/**\n * `stimeo mcp` — a zero-dependency Model Context Protocol server over stdio.\n *\n * Implements the JSON-RPC 2.0 subset an MCP client needs to use the Inspector\n * as read-only tools, resources, and prompts: `initialize`, the\n * `notifications/initialized` notification, `ping`, `tools/list`,\n * `tools/call`, `resources/list`, `resources/read`, `prompts/list`, and\n * `prompts/get` (newline-delimited messages, one per line). Hand-written on\n * purpose: the repo's constitution allows no runtime dependency beyond\n * `@hotwired/stimulus`, and this subset is small enough to conform to\n * directly (see the launch-kit/MCP plan §2.5, decision A).\n *\n * stdout carries protocol messages only; anything diagnostic must go to the\n * caller-provided error log (stderr in production).\n */\n\n/** Latest MCP protocol revision this server implements. */\nexport const LATEST_PROTOCOL_VERSION = \"2025-06-18\";\n\n/**\n * Revisions this server can speak. The tools-only subset is identical across\n * these revisions, so we echo whichever supported version the client asks for\n * and otherwise answer with the latest (per the MCP version-negotiation rule).\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n LATEST_PROTOCOL_VERSION,\n \"2025-03-26\",\n \"2024-11-05\",\n];\n\n/** JSON-RPC 2.0 error codes used by this server. */\nexport const JSONRPC_PARSE_ERROR = -32700;\nexport const JSONRPC_INVALID_REQUEST = -32600;\nexport const JSONRPC_METHOD_NOT_FOUND = -32601;\nexport const JSONRPC_INVALID_PARAMS = -32602;\nexport const JSONRPC_INTERNAL_ERROR = -32603;\n/**\n * MCP server-defined code (-32002). The spec assigns it both to requests sent\n * before `initialize` and to `resources/read` of an unknown URI; the two named\n * constants keep call sites self-documenting.\n */\nexport const JSONRPC_SERVER_NOT_INITIALIZED = -32002;\n/** See {@link JSONRPC_SERVER_NOT_INITIALIZED} — same spec-assigned code. */\nexport const JSONRPC_RESOURCE_NOT_FOUND = -32002;\n\n/** URI of the full-manifest resource. */\nexport const MANIFEST_RESOURCE_URI = \"stimeo://manifest\";\n/** URI prefix of the per-controller example resources. */\nexport const EXAMPLE_RESOURCE_PREFIX = \"stimeo://examples/\";\n\n/**\n * Request id this server accepts. MCP tightens bare JSON-RPC 2.0 here: a\n * request id MUST NOT be null, so `id: null` requests are rejected as invalid\n * rather than answered.\n */\ntype JsonRpcId = string | number;\n\n/**\n * Id an error response may carry: null only for messages whose id could not\n * be established (unparsable lines, malformed requests), per JSON-RPC 2.0.\n */\ntype JsonRpcErrorId = JsonRpcId | null;\n\ninterface JsonRpcSuccess {\n readonly jsonrpc: \"2.0\";\n readonly id: JsonRpcId;\n readonly result: unknown;\n}\n\ninterface JsonRpcError {\n readonly jsonrpc: \"2.0\";\n readonly id: JsonRpcErrorId;\n readonly error: { readonly code: number; readonly message: string };\n}\n\n/** Builds a serialized JSON-RPC success response. */\nfunction success(id: JsonRpcId, result: unknown): string {\n const response: JsonRpcSuccess = { jsonrpc: \"2.0\", id, result };\n return JSON.stringify(response);\n}\n\n/** Builds a serialized JSON-RPC error response. */\nfunction failure(id: JsonRpcErrorId, code: number, message: string): string {\n const response: JsonRpcError = { jsonrpc: \"2.0\", id, error: { code, message } };\n return JSON.stringify(response);\n}\n\n/** Narrows an unknown parsed message to a record. */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n}\n\n/**\n * One MCP session: a tiny state machine over parsed JSON-RPC messages.\n * Transport-free so tests can drive it line by line; {@link runMcpServer}\n * wires it to a readable stream.\n */\nexport class McpSession {\n #context: ToolContext;\n #initialized = false;\n\n constructor(context: ToolContext) {\n this.#context = context;\n }\n\n /**\n * Handles one newline-delimited message.\n *\n * @returns The serialized response line, or null when no response is due\n * (blank lines and notifications).\n */\n handleLine(line: string): string | null {\n const trimmed = line.trim();\n if (trimmed === \"\") return null;\n let message: unknown;\n try {\n message = JSON.parse(trimmed);\n } catch {\n return failure(null, JSONRPC_PARSE_ERROR, \"Parse error\");\n }\n return this.#handleMessage(message);\n }\n\n #handleMessage(message: unknown): string | null {\n const record = asRecord(message);\n // JSON-RPC batches were removed in MCP 2025-06-18; reject them explicitly.\n if (record === null || record.jsonrpc !== \"2.0\" || typeof record.method !== \"string\") {\n return failure(null, JSONRPC_INVALID_REQUEST, \"Invalid request\");\n }\n const method = record.method;\n const hasId = \"id\" in record;\n const id = record.id;\n if (!hasId) {\n // Notifications (initialized, cancelled, …) never get a response.\n return null;\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n // Covers `id: null` too: the MCP base protocol forbids null request\n // ids (unlike bare JSON-RPC 2.0), so it is rejected, not echoed.\n return failure(null, JSONRPC_INVALID_REQUEST, \"Invalid request id\");\n }\n return this.#handleRequest(id, method, record.params);\n }\n\n #handleRequest(id: JsonRpcId, method: string, params: unknown): string {\n if (method === \"initialize\") return this.#initialize(id, params);\n if (method === \"ping\") return success(id, {});\n if (!this.#initialized) {\n return failure(\n id,\n JSONRPC_SERVER_NOT_INITIALIZED,\n \"Server not initialized. Send an initialize request first.\",\n );\n }\n if (method === \"tools/list\") return success(id, { tools: TOOL_DESCRIPTORS });\n if (method === \"tools/call\") return this.#callTool(id, params);\n if (method === \"resources/list\") return success(id, { resources: this.#listResources() });\n if (method === \"resources/read\") return this.#readResource(id, params);\n if (method === \"prompts/list\") return success(id, { prompts: PROMPT_DESCRIPTORS });\n if (method === \"prompts/get\") return this.#getPrompt(id, params);\n return failure(id, JSONRPC_METHOD_NOT_FOUND, `Method not found: \"${method}\"`);\n }\n\n #initialize(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params) ?? {};\n const requested = typeof record.protocolVersion === \"string\" ? record.protocolVersion : \"\";\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested)\n ? requested\n : LATEST_PROTOCOL_VERSION;\n this.#initialized = true;\n return success(id, {\n protocolVersion,\n capabilities: {\n tools: { listChanged: false },\n resources: { subscribe: false, listChanged: false },\n prompts: { listChanged: false },\n },\n serverInfo: {\n name: \"stimeo-ui\",\n title: \"Stimeo UI Inspector\",\n version: this.#context.manifest.packageVersion,\n },\n instructions:\n \"Stimeo UI is a headless Stimulus UI framework for Rails. Use stimeo_catalog to \" +\n \"discover controllers, stimeo_controller for one controller's usage and \" +\n \"accessibility contract, stimeo_example for verified reference markup, and \" +\n \"stimeo_check to validate generated HTML/ERB before presenting it. The full \" +\n \"manifest and every example are also exposed as resources (stimeo:// URIs), and \" +\n \"the stimeo_build_ui / stimeo_fix_markup prompts bake this workflow into \" +\n \"user-invokable templates.\",\n });\n }\n\n #getPrompt(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params);\n const name = record?.name;\n if (typeof name !== \"string\") {\n return failure(id, JSONRPC_INVALID_PARAMS, 'prompts/get requires a string \"name\" param.');\n }\n try {\n return success(id, getPrompt(name, record?.arguments));\n } catch (error) {\n if (error instanceof InvalidPromptRequestError) {\n // Unknown prompt names and bad arguments are protocol errors per the\n // MCP prompts spec (unlike tool execution failures).\n return failure(id, JSONRPC_INVALID_PARAMS, error.message);\n }\n const message = error instanceof Error ? error.message : String(error);\n return failure(id, JSONRPC_INTERNAL_ERROR, `Internal error: ${message}`);\n }\n }\n\n /** Static resource listing: the manifest plus one example per controller. */\n #listResources(): readonly Record<string, unknown>[] {\n const resources: Record<string, unknown>[] = [\n {\n uri: MANIFEST_RESOURCE_URI,\n name: \"manifest\",\n title: \"Stimeo UI controller manifest\",\n description:\n \"The full reflected manifest: every controller's targets, values, actions, \" +\n \"events, required targets, and accessibility contract.\",\n mimeType: \"application/json\",\n },\n ];\n for (const id of Object.keys(this.#context.examples.examples).sort()) {\n resources.push({\n uri: `${EXAMPLE_RESOURCE_PREFIX}${id}`,\n name: id,\n title: `Example markup — ${id}`,\n description: `Verified catalog demo markup for ${id} (passes stimeo_check).`,\n mimeType: \"text/x-erb\",\n });\n }\n return resources;\n }\n\n #readResource(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params);\n const uri = record?.uri;\n if (typeof uri !== \"string\") {\n return failure(id, JSONRPC_INVALID_PARAMS, 'resources/read requires a string \"uri\" param.');\n }\n if (uri === MANIFEST_RESOURCE_URI) {\n return success(id, {\n contents: [\n {\n uri,\n mimeType: \"application/json\",\n text: JSON.stringify(this.#context.manifest, null, 2),\n },\n ],\n });\n }\n if (uri.startsWith(EXAMPLE_RESOURCE_PREFIX)) {\n const exampleId = uri.slice(EXAMPLE_RESOURCE_PREFIX.length);\n const entry = getOwn(this.#context.examples.examples, exampleId);\n if (entry) {\n return success(id, {\n contents: [{ uri, mimeType: \"text/x-erb\", text: entry.source }],\n });\n }\n }\n return failure(id, JSONRPC_RESOURCE_NOT_FOUND, `Resource not found: \"${uri}\"`);\n }\n\n #callTool(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params);\n const name = record?.name;\n if (typeof name !== \"string\") {\n return failure(id, JSONRPC_INVALID_PARAMS, 'tools/call requires a string \"name\" param.');\n }\n try {\n const result = callTool(this.#context, name, record?.arguments);\n return success(id, {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n structuredContent: result,\n });\n } catch (error) {\n if (error instanceof InvalidToolArgsError) {\n return failure(id, JSONRPC_INVALID_PARAMS, error.message);\n }\n if (error instanceof ToolExecutionError) {\n // Tool execution errors flow back as results so the model can read\n // the message and self-correct (MCP tools spec).\n return success(id, {\n content: [{ type: \"text\", text: error.message }],\n isError: true,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return failure(id, JSONRPC_INTERNAL_ERROR, `Internal error: ${message}`);\n }\n }\n}\n\n/** I/O seams for {@link runMcpServer}; injectable for tests. */\nexport interface McpServerIo {\n /** Stream carrying newline-delimited JSON-RPC messages (stdin in production). */\n readonly input: Readable;\n /** Sink for one serialized response line (stdout in production). */\n readonly write: (line: string) => void;\n /**\n * Tool-context loader (the bundled `dist/inspector/manifest.json` and\n * `examples.json` in production).\n */\n readonly load: () => ToolContext;\n /** Diagnostic sink; must never be stdout (protocol-only). */\n readonly logError?: (message: string) => void;\n}\n\n/**\n * Runs the stdio server loop: one JSON-RPC message per input line, one\n * response per output line. Resolves when the input stream closes (the MCP\n * client disconnecting), which is the server's shutdown signal. Declared\n * async so a failing manifest load rejects the returned promise instead of\n * throwing synchronously past the caller's rejection handler.\n */\nexport async function runMcpServer(io: McpServerIo): Promise<void> {\n const session = new McpSession(io.load());\n const lines = createInterface({ input: io.input, crlfDelay: Number.POSITIVE_INFINITY });\n return new Promise((resolve) => {\n lines.on(\"line\", (line) => {\n try {\n const response = session.handleLine(line);\n if (response !== null) io.write(response);\n } catch (error) {\n // The session already converts per-request failures into JSON-RPC\n // errors; this guards the loop itself so one bad line cannot kill\n // the server.\n io.logError?.(error instanceof Error ? error.message : String(error));\n }\n });\n lines.on(\"close\", resolve);\n });\n}\n","import process from \"node:process\";\nimport { loadExamplesIndex, loadManifest, runCli } from \"./cli\";\nimport { runMcpServer } from \"./mcp/server\";\n\n/**\n * Executable entry point for the `stimeo` bin. Kept separate from {@link runCli}\n * so the CLI logic can be imported by tests without triggering `process.exit`.\n * A Node shebang is prepended to the built file by `scripts/postbuild.ts`.\n *\n * `stimeo mcp` is dispatched here rather than inside {@link runCli} because it\n * is not a run-to-completion command: it starts a resident stdio server that\n * only exits when the client closes stdin. Everything else keeps the original\n * synchronous exit-code contract.\n */\nconst argv = process.argv.slice(2);\n\nif (argv[0] === \"mcp\") {\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n process.exit(runCli([\"--help\"]));\n }\n // A disappearing client closes our stdout pipe; exit quietly on EPIPE\n // instead of crashing with an unhandled stream error.\n process.stdout.on(\"error\", (error: NodeJS.ErrnoException) => {\n process.exit(error.code === \"EPIPE\" ? 0 : 1);\n });\n runMcpServer({\n input: process.stdin,\n write: (line) => {\n process.stdout.write(`${line}\\n`);\n },\n load: () => ({ manifest: loadManifest(), examples: loadExamplesIndex() }),\n logError: (message) => {\n process.stderr.write(`stimeo mcp: ${message}\\n`);\n },\n }).then(\n // Set the exit code instead of calling process.exit so any buffered\n // stdout responses are flushed before the process ends.\n () => {\n process.exitCode = 0;\n },\n (error: unknown) => {\n process.stderr.write(\n `stimeo mcp: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n process.exitCode = 1;\n },\n );\n} else {\n process.exit(runCli(argv));\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/inspector/erb.ts","../../src/inspector/extract.ts","../../src/inspector/html_parser.ts","../../src/inspector/types.ts","../../src/inspector/check.ts","../../src/inspector/examples.ts","../../src/inspector/files.ts","../../src/inspector/manifest_io.ts","../../src/inspector/cli.ts","../../src/inspector/mcp/prompts.ts","../../src/inspector/mcp/tools.ts","../../src/inspector/mcp/server.ts","../../src/inspector/cli_bin.ts"],"names":["j","readFileSync","argv","manifest","process"],"mappings":";;;;;;;;;AAkBO,SAAS,cAAc,MAAA,EAAwB;AACpD,EAAA,OAAO,MAAA,CAAO,QAAQ,eAAA,EAAiB,CAAC,UAAU,KAAA,CAAM,OAAA,CAAQ,QAAA,EAAU,GAAG,CAAC,CAAA;AAChF;;;ACZA,IAAM,gBAAA,GAAmB,UAAA;AAMlB,SAAS,UAAU,KAAA,EAAuB;AAC/C,EAAA,OAAO,KAAA,CAAM,OAAA,CAAQ,UAAA,EAAY,CAAC,MAAA,EAAQ,SAAiB,CAAA,CAAA,EAAI,IAAA,CAAK,WAAA,EAAa,CAAA,CAAE,CAAA;AACrF;AAKO,SAAS,sBAAsB,mBAAA,EAAuC;AAC3E,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,KAAA,MAAW,KAAA,IAAS,mBAAA,CAAoB,KAAA,CAAM,KAAK,CAAA,EAAG;AACpD,IAAA,IAAI,MAAM,UAAA,CAAW,gBAAgB,CAAA,EAAG,IAAA,CAAK,IAAI,KAAK,CAAA;AAAA,EACxD;AACA,EAAA,OAAO,CAAC,GAAG,IAAI,CAAA;AACjB;AAMO,SAAS,gBAAgB,QAAA,EAAiC;AAC/D,EAAA,MAAM,KAAA,GAAQ,4CAAA,CAA6C,IAAA,CAAK,QAAQ,CAAA;AACxE,EAAA,OAAO,KAAA,GAAQ,CAAC,CAAA,IAAK,IAAA;AACvB;AAsBO,SAAS,cAAA,CACd,UACA,gBAAA,EACwB;AACxB,EAAA,MAAM,KAAA,GAAQ,mCAAA,CAAoC,IAAA,CAAK,QAAQ,CAAA;AAC/D,EAAA,IAAI,CAAC,OAAO,OAAO,IAAA;AACnB,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA;AAE1B,EAAA,IAAI,IAAA,GAA0D,IAAA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ralizes ERB so the HTML parser only ever sees static markup.\n *\n * Every ERB tag — `<% %>`, `<%= %>`, `<%# %>`, plus the whitespace-trimming\n * variants `<%- -%>` — is replaced with spaces. Newlines inside the tag are\n * preserved so that 1-based line/column positions used in diagnostics line up\n * with the original source.\n *\n * Because ERB is blanked rather than interpreted, dynamically-generated markup\n * is naturally excluded from checking: a dynamic identifier such as\n * `data-controller=\"<%= id %>\"` collapses to an empty attribute value and a\n * dynamic attribute name such as `data-<%= x %>-target` no longer matches the\n * `stimeo--*` patterns. This is the intended \"dynamic attributes are out of\n * scope\" behavior.\n *\n * @param source - Raw HTML/ERB source.\n * @returns The source with all ERB tags replaced by position-preserving spaces.\n */\nexport function neutralizeErb(source: string): string {\n return source.replace(/<%[\\s\\S]*?%>/g, (match) => match.replace(/[^\\n]/g, \" \"));\n}\n","/**\n * Pure helpers for recognizing `stimeo--*` attributes within parsed markup.\n *\n * These functions know nothing about files or the manifest — they only decode\n * Stimulus's attribute conventions, scoped strictly to the `stimeo--`\n * namespace so a consumer's own controllers are never inspected.\n */\n\nconst NAMESPACE_PREFIX = \"stimeo--\";\n\n/**\n * Converts a Stimulus value name to its attribute token, mirroring Stimulus's\n * own dasherize (e.g. `rootMargin` → `root-margin`).\n */\nexport function dasherize(value: string): string {\n return value.replace(/([A-Z])/g, (_match, char: string) => `-${char.toLowerCase()}`);\n}\n\n/** Extracts the `stimeo--*` identifiers listed in a `data-controller` value.\n * Duplicates are collapsed (Stimulus connects a repeated identifier once), which\n * keeps downstream scope-based diagnostics from being reported multiple times. */\nexport function controllerIdentifiers(dataControllerValue: string): string[] {\n const seen = new Set<string>();\n for (const token of dataControllerValue.split(/\\s+/)) {\n if (token.startsWith(NAMESPACE_PREFIX)) seen.add(token);\n }\n return [...seen];\n}\n\n/**\n * If `attrName` is an Stimeo target attribute (`data-{identifier}-target`),\n * returns the controller identifier; otherwise `null`.\n */\nexport function parseTargetAttr(attrName: string): string | null {\n const match = /^data-(stimeo--[a-z0-9][a-z0-9-]*)-target$/.exec(attrName);\n return match?.[1] ?? null;\n}\n\n/** Result of decoding a `data-{identifier}-{value}-value` attribute. */\nexport interface ParsedValueAttr {\n /** Resolved identifier, or `null` when it matches no known controller. */\n readonly identifier: string | null;\n /** The dasherized value token (e.g. `root-margin`), best-effort when unresolved. */\n readonly valueToken: string;\n}\n\n/**\n * Decodes an Stimeo value attribute (`data-{identifier}-{value}-value`).\n *\n * Identifiers may themselves contain hyphens (e.g. `stimeo--command-palette`),\n * so the boundary between identifier and value name is ambiguous from the\n * attribute name alone. We disambiguate against the set of known identifiers,\n * preferring the longest match.\n *\n * @param attrName - The lowercased attribute name.\n * @param knownIdentifiers - All identifiers present in the manifest.\n * @returns The decoded attribute, or `null` if it is not an Stimeo value attr.\n */\nexport function parseValueAttr(\n attrName: string,\n knownIdentifiers: readonly string[],\n): ParsedValueAttr | null {\n const match = /^data-(stimeo--[a-z0-9-]+)-value$/.exec(attrName);\n if (!match) return null;\n const inner = match[1] ?? \"\"; // identifier + \"-\" + valueToken\n\n let best: { identifier: string; valueToken: string } | null = null;\n for (const id of knownIdentifiers) {\n if (inner.startsWith(`${id}-`)) {\n const valueToken = inner.slice(id.length + 1);\n if (valueToken.length > 0 && (!best || id.length > best.identifier.length)) {\n best = { identifier: id, valueToken };\n }\n }\n }\n if (best) return best;\n\n // Unknown identifier: best-effort split at the first segment after the prefix.\n const rest = inner.slice(NAMESPACE_PREFIX.length);\n const dash = rest.indexOf(\"-\");\n const identifierGuess = dash === -1 ? inner : `${NAMESPACE_PREFIX}${rest.slice(0, dash)}`;\n const valueGuess = dash === -1 ? \"\" : rest.slice(dash + 1);\n return { identifier: null, valueToken: valueGuess || identifierGuess };\n}\n\n/** An Stimeo `data-action` descriptor decoded into its controller and method. */\nexport interface ActionDescriptor {\n /** The `stimeo--*` controller identifier (e.g. `stimeo--menu`). */\n readonly identifier: string;\n /** The action method name after `#` (e.g. `toggle`), or `\"\"` if absent. */\n readonly method: string;\n}\n\n/**\n * Decodes the Stimeo `data-action` descriptors in an attribute value, e.g.\n * `click->stimeo--menu#toggle keydown->stimeo--menu#onItemKeydown` yields one\n * entry per descriptor. Non-`stimeo--` controllers are skipped (their action\n * surface is out of scope). The method name is read up to the first action\n * option (`:prevent`, `:stop`, …), mirroring Stimulus's descriptor grammar.\n */\nexport function actionDescriptors(dataActionValue: string): ActionDescriptor[] {\n const descriptors: ActionDescriptor[] = [];\n for (const descriptor of dataActionValue.split(/\\s+/)) {\n const hash = descriptor.indexOf(\"#\");\n if (hash === -1) continue;\n let lhs = descriptor.slice(0, hash);\n const arrow = lhs.indexOf(\"->\");\n if (arrow !== -1) lhs = lhs.slice(arrow + 2);\n if (!lhs.startsWith(NAMESPACE_PREFIX)) continue;\n const method = /^[a-zA-Z_$][\\w$]*/.exec(descriptor.slice(hash + 1))?.[0] ?? \"\";\n descriptors.push({ identifier: lhs, method });\n }\n return descriptors;\n}\n\n/**\n * Extracts the `stimeo--*` controller identifiers referenced in a\n * `data-action` value, e.g. `click->stimeo--menu#toggle` yields\n * `[\"stimeo--menu\"]`. Convenience wrapper over {@link actionDescriptors}.\n */\nexport function actionIdentifiers(dataActionValue: string): string[] {\n return actionDescriptors(dataActionValue).map((d) => d.identifier);\n}\n\n/** Whether an attribute name belongs to the Stimeo namespace. */\nexport function isStimeoDataAttr(attrName: string): boolean {\n return attrName.startsWith(`data-${NAMESPACE_PREFIX}`);\n}\n","/**\n * A minimal, dependency-free HTML tokenizer/tree builder.\n *\n * The Inspector deliberately ships **zero runtime dependencies** beyond the\n * Stimulus peer (see project invariants), so rather than pull in a DOM library\n * we build just enough of a tree to answer the only questions the checker asks:\n * \"which `stimeo--*` attributes exist, where, and inside which controller\n * scope?\". The parser is intentionally lenient — real-world ERB output has\n * unclosed tags and stray markup — and never throws.\n *\n * It is **not** a spec-compliant HTML parser and should not be used for\n * anything beyond static attribute inspection.\n */\n\n/** A parsed attribute, with the source position of its name. */\nexport interface ParsedAttr {\n /** Lowercased attribute name (HTML attribute names are case-insensitive). */\n readonly name: string;\n /** Attribute value (without surrounding quotes); empty for boolean attrs. */\n readonly value: string;\n /** 1-based line of the attribute name. */\n readonly line: number;\n /** 1-based column of the attribute name. */\n readonly column: number;\n /**\n * Absolute source offset where the value text begins (inside the quotes);\n * absent for boolean attributes. ERB neutralization preserves offsets, so a\n * consumer can map the range back onto the *raw* source — this is how the\n * checker tells an authored value from a dynamically-generated one.\n */\n readonly valueStart?: number;\n /** Absolute source offset just past the value text; see {@link valueStart}. */\n readonly valueEnd?: number;\n}\n\n/** An element node in the lenient tree. */\nexport interface ElementNode {\n /** Lowercased tag name; the synthetic root uses `#root`. */\n readonly tag: string;\n readonly attrs: readonly ParsedAttr[];\n readonly children: ElementNode[];\n parent: ElementNode | null;\n /** 1-based line of the tag's `<`. */\n readonly line: number;\n /** 1-based column of the tag's `<`. */\n readonly column: number;\n}\n\n/** Elements that never have children and so are never pushed onto the stack. */\nconst VOID_ELEMENTS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Elements whose content is raw text (no nested elements to parse). */\nconst RAW_TEXT_ELEMENTS = new Set([\"script\", \"style\", \"textarea\", \"title\"]);\n\nconst WHITESPACE = new Set([\" \", \"\\t\", \"\\n\", \"\\r\", \"\\f\"]);\n\n/** Maps absolute string offsets to 1-based line/column positions. */\nclass PositionIndex {\n readonly #lineStarts: number[] = [0];\n\n constructor(source: string) {\n for (let i = 0; i < source.length; i++) {\n if (source[i] === \"\\n\") this.#lineStarts.push(i + 1);\n }\n }\n\n at(offset: number): { line: number; column: number } {\n // Binary search for the last line start that is <= offset.\n let lo = 0;\n let hi = this.#lineStarts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if ((this.#lineStarts[mid] ?? 0) <= offset) lo = mid;\n else hi = mid - 1;\n }\n return { line: lo + 1, column: offset - (this.#lineStarts[lo] ?? 0) + 1 };\n }\n}\n\n/**\n * Parses HTML (already ERB-neutralized) into a lenient element tree.\n *\n * @param source - HTML source to parse.\n * @returns The synthetic `#root` node whose children are the top-level elements.\n */\nexport function parseHtml(source: string): ElementNode {\n const pos = new PositionIndex(source);\n const len = source.length;\n /** Bounds-safe character access (out of range yields an empty string). */\n const ch = (k: number): string => (k >= 0 && k < len ? (source[k] as string) : \"\");\n\n const root: ElementNode = {\n tag: \"#root\",\n attrs: [],\n children: [],\n parent: null,\n line: 1,\n column: 1,\n };\n const stack: ElementNode[] = [root];\n let i = 0;\n\n const top = (): ElementNode => stack[stack.length - 1] as ElementNode;\n\n while (i < len) {\n if (ch(i) !== \"<\") {\n i++;\n continue;\n }\n\n const next = ch(i + 1);\n\n // Comment: <!-- ... -->\n if (source.startsWith(\"<!--\", i)) {\n const end = source.indexOf(\"-->\", i + 4);\n i = end === -1 ? len : end + 3;\n continue;\n }\n // Markup declaration (<!DOCTYPE ...>) or processing instruction (<? ... ?>).\n if (next === \"!\" || next === \"?\") {\n const end = source.indexOf(\">\", i);\n i = end === -1 ? len : end + 1;\n continue;\n }\n // End tag: </name>\n if (next === \"/\") {\n let j = i + 2;\n let name = \"\";\n while (j < len && ch(j) !== \">\" && !WHITESPACE.has(ch(j))) {\n name += ch(j);\n j++;\n }\n const end = source.indexOf(\">\", j);\n i = end === -1 ? len : end + 1;\n closeTag(stack, name.toLowerCase());\n continue;\n }\n // Not a tag start (e.g. a stray \"<\"); treat as text.\n if (!/[a-zA-Z]/.test(next)) {\n i++;\n continue;\n }\n\n // Start tag.\n const tagStart = i;\n let j = i + 1;\n let tagName = \"\";\n while (j < len && !WHITESPACE.has(ch(j)) && ch(j) !== \">\" && ch(j) !== \"/\") {\n tagName += ch(j);\n j++;\n }\n const lowerTag = tagName.toLowerCase();\n const attrs: ParsedAttr[] = [];\n\n // Parse attributes until the tag closes.\n let selfClosing = false;\n while (j < len) {\n while (j < len && WHITESPACE.has(ch(j))) j++;\n if (j >= len) break;\n if (ch(j) === \">\") {\n j++;\n break;\n }\n if (ch(j) === \"/\") {\n selfClosing = true;\n j++;\n continue;\n }\n\n // Attribute name.\n const nameStart = j;\n let attrName = \"\";\n while (j < len && !WHITESPACE.has(ch(j)) && ch(j) !== \"=\" && ch(j) !== \">\" && ch(j) !== \"/\") {\n attrName += ch(j);\n j++;\n }\n\n let attrValue = \"\";\n let valueStart: number | undefined;\n let valueEnd: number | undefined;\n // Optional value.\n let k = j;\n while (k < len && WHITESPACE.has(ch(k))) k++;\n if (ch(k) === \"=\") {\n k++;\n while (k < len && WHITESPACE.has(ch(k))) k++;\n const quote = ch(k);\n if (quote === '\"' || quote === \"'\") {\n k++;\n const valStart = k;\n while (k < len && ch(k) !== quote) k++;\n attrValue = source.slice(valStart, k);\n valueStart = valStart;\n valueEnd = k;\n k++; // skip closing quote\n } else {\n const valStart = k;\n while (k < len && !WHITESPACE.has(ch(k)) && ch(k) !== \">\") k++;\n attrValue = source.slice(valStart, k);\n valueStart = valStart;\n valueEnd = k;\n }\n j = k;\n }\n\n if (attrName.length > 0) {\n const p = pos.at(nameStart);\n attrs.push({\n name: attrName.toLowerCase(),\n value: attrValue,\n line: p.line,\n column: p.column,\n valueStart,\n valueEnd,\n });\n }\n }\n\n const startPos = pos.at(tagStart);\n const node: ElementNode = {\n tag: lowerTag,\n attrs,\n children: [],\n parent: top(),\n line: startPos.line,\n column: startPos.column,\n };\n top().children.push(node);\n\n i = j;\n\n if (selfClosing || VOID_ELEMENTS.has(lowerTag)) {\n continue;\n }\n\n if (RAW_TEXT_ELEMENTS.has(lowerTag)) {\n // Skip raw-text content so `<` inside scripts/styles is not parsed as markup.\n const closeNeedle = `</${lowerTag}`;\n const idx = source.toLowerCase().indexOf(closeNeedle, i);\n if (idx === -1) {\n i = len;\n } else {\n const gt = source.indexOf(\">\", idx);\n i = gt === -1 ? len : gt + 1;\n }\n continue;\n }\n\n stack.push(node);\n }\n\n return root;\n}\n\n/** Pops the stack down to (and including) the nearest matching open tag. */\nfunction closeTag(stack: ElementNode[], name: string): void {\n for (let depth = stack.length - 1; depth >= 1; depth--) {\n if (stack[depth]?.tag === name) {\n stack.length = depth;\n return;\n }\n }\n // No matching open tag — ignore the stray end tag.\n}\n\n/** Depth-first walk over every element node (excluding the synthetic root). */\nexport function walk(root: ElementNode, visit: (node: ElementNode) => void): void {\n for (const child of root.children) {\n visit(child);\n walk(child, visit);\n }\n}\n","/**\n * Shared types for the Stimeo Inspector CLI (`stimeo check`).\n *\n * The Inspector statically checks HTML/ERB against a *manifest* describing the\n * official `stimeo--` controllers. The same engine powers both the project's own\n * contract checks (e.g. `stimeo check app/views`) and the\n * user-facing product feature; it is therefore intentionally input-path\n * agnostic.\n */\n\n/**\n * Per-controller manifest entry.\n *\n * `targets` and `values` are reflected from the controller class\n * (`static targets` / `static values`). `actions` and `events` are reflected\n * from co-located `static actions` / `static events` declarations — Stimulus\n * keeps no registry of action methods, and TypeScript `private` survives on the\n * prototype, so the public action/event surface cannot be told apart from\n * internal helpers by reflection alone; it must be declared explicitly in the\n * implementation. `requiredTargets` is a hand-written structure rule (Stimulus\n * reflection cannot express \"required\").\n */\nexport interface ControllerManifest {\n /** Target names declared via `static targets`. */\n readonly targets: readonly string[];\n /** Value names (camelCase) declared via `static values`. */\n readonly values: readonly string[];\n /**\n * Public action method names declared via `static actions`, wired by\n * consumers as `data-action=\"…-><identifier>#<action>\"`.\n */\n readonly actions: readonly string[];\n /**\n * Logical event names declared via `static events`, dispatched as\n * `<identifier>:<event>` (Stimulus `this.dispatch(\"<event>\")`).\n */\n readonly events: readonly string[];\n /** Targets that must be present at least once inside the controller scope. */\n readonly requiredTargets: readonly string[];\n /**\n * Accessibility requirements the *consumer's markup* must satisfy (stage 3):\n * ARIA attributes the controller does **not** set at runtime and therefore\n * relies on the author to provide (e.g. a dialog's `role`/`aria-modal`/name).\n * Attributes the controller manages itself (e.g. tabs' `aria-selected`) are\n * deliberately excluded — requiring them would be noise.\n */\n readonly a11y: readonly A11yRequirement[];\n /**\n * Keyboard prerequisites (stage 3, schema v4): targets whose documented\n * contract makes the *author* responsible for focusability — the controller\n * moves focus (or relies on the Tab order) but never writes `tabindex` for\n * them. Each listed target must be natively focusable or carry `tabindex`.\n * Targets whose controller initializes a roving tabindex on connect (tabs,\n * toolbar, radio group, …) are deliberately excluded.\n */\n readonly keyboard: readonly KeyboardRequirement[];\n /**\n * Author-futile attributes (stage 3, schema v4): ARIA the controller\n * recomputes wholesale at runtime, where an authored value can neither\n * survive nor serve as pre-connect initial state (e.g. a combobox input's\n * `aria-activedescendant`). Authoring one is reported as a *warning*.\n * Attributes whose authored value is a legitimate initial (`aria-expanded`,\n * `aria-checked`, `aria-valuenow`, …) are deliberately excluded.\n */\n readonly managedAria: readonly ManagedAriaRule[];\n /**\n * Conditional cross-controller composition rules (stage 3, schema v5):\n * value-alignment contracts between this controller and a co-located\n * companion (e.g. sortable's sort axis vs roving's `orientation`). Prose-only\n * before v5, where a dropped or misaligned value silently broke keyboard\n * interaction while `stimeo check` passed.\n */\n readonly compositions: readonly CompositionRule[];\n}\n\n/**\n * A single accessibility requirement on a controller's markup (Inspector\n * stage 3). At least one of {@link attrs} must be present on the\n * {@link target} element; when {@link values} is given, the present\n * attribute's value must be one of them. {@link or} widens the requirement\n * with alternative attribute/value groups — the requirement is satisfied when\n * *any* group is (schema v4; e.g. `role=\"status\"` **or** `aria-live`).\n */\nexport interface A11yRequirement {\n /**\n * Target name the requirement applies to; the empty string `\"\"` means the\n * controller's own scope element (the `data-controller` node).\n */\n readonly target: string;\n /**\n * Candidate attribute names — at least one must be present. A list expresses\n * \"any of\" (e.g. `aria-labelledby` *or* `aria-label` for an accessible name).\n */\n readonly attrs: readonly string[];\n /** Allowed values for the matched attribute; omit to accept any value. */\n readonly values?: readonly string[];\n /**\n * Alternative attribute groups, each with its **own** allowed-value set —\n * something `attrs` alone cannot express (its `values` apply to every listed\n * attribute). A present attribute with a wrong value is still reported even\n * when another group is satisfied: an invalid authored value is an error in\n * its own right (e.g. `aria-live=\"off\"` silencing a satisfied `role=\"status\"`).\n */\n readonly or?: readonly A11yAlternative[];\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/** One alternative attribute group of an {@link A11yRequirement} (`or`). */\nexport interface A11yAlternative {\n /** Candidate attribute names — at least one must be present. */\n readonly attrs: readonly string[];\n /** Allowed values for the matched attribute; omit to accept any value. */\n readonly values?: readonly string[];\n}\n\n/**\n * A keyboard prerequisite (stage 3, schema v4): every present element of\n * {@link target} must be reachable by keyboard. What \"reachable\" means depends\n * on how the controller drives focus, expressed by {@link reach}:\n *\n * - `\"tab\"` (Tab stop): the element is a steady tab stop the user reaches with\n * Tab, so it must be natively tab-focusable (`button`, `input` except\n * `type=\"hidden\"`, `select`, `textarea`, `summary`, `a[href]`, `area[href]`,\n * or `contenteditable`) **or** carry `tabindex=\"0\"` (any non-negative value).\n * A `tabindex=\"-1\"` removes it from the Tab order and therefore **fails** —\n * this is the case a mere \"has tabindex\" presence check would miss.\n * - `\"focus\"` (roving / programmatic): the controller moves focus with\n * `element.focus()`, so the element only has to be focusable *at all* —\n * natively focusable **or** carrying any valid `tabindex` (including the\n * roving `-1`).\n *\n * Only the per-element floor is checked; the roving set-level invariant\n * (\"exactly one item is `tabindex=\"0\"`\") is runtime state owned by the\n * controller and deliberately out of scope.\n */\nexport interface KeyboardRequirement {\n /** Target name the requirement applies to (never the scope element). */\n readonly target: string;\n /**\n * How the user reaches the target. Defaults to `\"tab\"` (the common case —\n * most operation points are steady Tab stops); set `\"focus\"` only for\n * targets the controller roves via programmatic focus.\n */\n readonly reach?: \"tab\" | \"focus\";\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/**\n * An author-futile attribute rule (stage 3, schema v4): authoring any of\n * {@link attrs} on the {@link target} element draws a `managed-aria`\n * **warning** — the controller recomputes the attribute wholesale, so the\n * authored value is dead weight that misleads readers of the markup.\n */\nexport interface ManagedAriaRule {\n /**\n * Target name the rule applies to; the empty string `\"\"` means the\n * controller's own scope element.\n */\n readonly target: string;\n /** Attribute names the controller owns outright. */\n readonly attrs: readonly string[];\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/**\n * A conditional cross-controller composition rule (stage 3, schema v5): when a\n * companion controller is co-located on one of the host's elements, one of the\n * companion's values must align with a value of the host. The rule fires only\n * when {@link coController} is actually declared there — composition itself\n * stays optional (whether to compose is the author's call; the rule only\n * guards *how*).\n *\n * Both sides are compared by their **effective** value — the authored\n * attribute, or the declared default when the attribute is absent — because\n * the misalignments these rules exist for are default asymmetries (e.g.\n * sortable defaults its `orientation` to `vertical` while roving defaults to\n * `horizontal`, so a bare composition is silently broken). The defaults are\n * duplicated here from the controllers' `static values`; a manifest test\n * guards them against drift.\n */\nexport interface CompositionRule {\n /**\n * Host target whose element hosts the companion; the empty string `\"\"`\n * means the controller's own scope element.\n */\n readonly target: string;\n /**\n * Check the scope element when {@link target} is absent — for optional\n * container targets whose documented fallback is the scope element itself\n * (e.g. sortable's `list`).\n */\n readonly fallbackToScope?: boolean;\n /** Companion controller identifier expected in the element's `data-controller`. */\n readonly coController: string;\n /**\n * Condition on the host's own value (read from the scope element); omit for\n * unconditional rules. The rule applies only when the host's effective\n * value is one of `equals`.\n */\n readonly when?: {\n /** Host value name (camelCase, as declared in `static values`). */\n readonly value: string;\n /** Effective host values that arm the rule. */\n readonly equals: readonly string[];\n /** The host value's declared default, used when the attribute is absent. */\n readonly default: string;\n };\n /** Requirement on the companion's value (read from the companion's element). */\n readonly require: {\n /** Companion value name (camelCase, as declared in `static values`). */\n readonly value: string;\n /**\n * Allowed effective values, **ordered**: the first entry is the canonical\n * alignment and feeds the machine fix when an authored value is wrong.\n */\n readonly oneOf: readonly string[];\n /** The companion value's declared default, used when the attribute is absent. */\n readonly default: string;\n };\n /** Human-readable fix suggestion shown by the CLI (stage 4). */\n readonly suggestion: string;\n}\n\n/**\n * The bundled manifest. `schemaVersion` tracks the manifest *format*;\n * `packageVersion` tracks the `stimeo-ui` release it was generated from so a\n * consumer can confirm the check matches their installed version.\n */\nexport interface Manifest {\n readonly schemaVersion: number;\n readonly packageVersion: string;\n /** Keyed by controller identifier, e.g. `stimeo--menu`. */\n readonly controllers: Readonly<Record<string, ControllerManifest>>;\n}\n\n/** Hand-written structure rules, merged into the reflected manifest. */\nexport type StructureRules = Readonly<\n Record<string, { readonly requiredTargets?: readonly string[] }>\n>;\n\n/** Hand-written accessibility rules (stage 3), merged into the manifest. */\nexport type A11yRules = Readonly<Record<string, readonly A11yRequirement[]>>;\n\n/** Hand-written keyboard prerequisites (stage 3), merged into the manifest. */\nexport type KeyboardRules = Readonly<Record<string, readonly KeyboardRequirement[]>>;\n\n/** Hand-written author-futile attribute rules, merged into the manifest. */\nexport type ManagedAriaRules = Readonly<Record<string, readonly ManagedAriaRule[]>>;\n\n/** Hand-written composition rules (stage 3), merged into the manifest. */\nexport type CompositionRules = Readonly<Record<string, readonly CompositionRule[]>>;\n\n/** Severity of a diagnostic. Only `error` affects the process exit code. */\nexport type DiagnosticSeverity = \"error\" | \"warning\";\n\n/**\n * Stable identifiers for the kinds of problems the Inspector reports. Useful\n * for testing, machine-readable output, and `data-stimeo-ignore` suppression\n * lists (which is why the set also exists as a runtime array).\n */\nexport const DIAGNOSTIC_CODES = [\n \"unknown-controller\",\n \"unknown-target\",\n \"unknown-value\",\n \"unknown-action-controller\",\n \"unknown-action-method\",\n \"orphan-target\",\n \"missing-required-target\",\n \"missing-aria\",\n \"invalid-aria-value\",\n \"keyboard-inaccessible\",\n \"unresolved-idref\",\n \"managed-aria\",\n \"composition-mismatch\",\n \"unknown-ignore-code\",\n] as const;\n\n/** See {@link DIAGNOSTIC_CODES}. */\nexport type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number];\n\n/**\n * A machine-applicable fix for a diagnostic: replace the source text in\n * `[start, end)` with `text`. Only emitted when the engine can compute the\n * exact range with confidence — a typo'd token inside an attribute value, or\n * a single-valued ARIA correction. Editors surface it as a quick fix; the\n * human-readable `suggestion` stays the fallback for everything else.\n */\nexport interface DiagnosticFix {\n /** Absolute source offset where the replacement starts. */\n readonly start: number;\n /** Absolute source offset just past the replaced text. */\n readonly end: number;\n /** Replacement text. */\n readonly text: string;\n /** Short imperative label for editor UI, e.g. `Replace with \"stimeo--menu\"`. */\n readonly title: string;\n}\n\n/** A single problem found in a source file. */\nexport interface Diagnostic {\n readonly code: DiagnosticCode;\n readonly severity: DiagnosticSeverity;\n readonly message: string;\n /** 1-based line where the problem was detected. */\n readonly line: number;\n /** 1-based column where the problem was detected. */\n readonly column: number;\n /**\n * Length in source characters of the anchored token starting at `column` —\n * the attribute name for attribute-anchored diagnostics, or the opening\n * `<tag` for element-anchored ones. Lets editors underline the exact token\n * instead of guessing a word boundary. Optional so hand-built or historical\n * reports without it stay valid; consumers should fall back to `1`.\n */\n readonly length?: number;\n /**\n * Optional fix suggestion (stage 4): the corrected attribute to add, or the\n * nearest known name for a likely typo. Rendered on its own line by the CLI.\n */\n readonly suggestion?: string;\n /** Machine-applicable replacement (stage 4), when one can be computed safely. */\n readonly fix?: DiagnosticFix;\n}\n\n/** Diagnostics grouped by the file they came from. */\nexport interface FileReport {\n readonly file: string;\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/**\n * Machine-readable result of `stimeo check --json`: the structured counterpart\n * of the human report, for editor tooling and CI. `files` lists only sources\n * that produced diagnostics; `ok` is\n * true when no error-severity diagnostic was found (mirrors the exit code).\n */\nexport interface CheckReport {\n /** True when no error-severity diagnostics were found. */\n readonly ok: boolean;\n /** Total number of HTML/ERB files scanned. */\n readonly checkedFiles: number;\n /** Count of error-severity diagnostics across all files. */\n readonly errorCount: number;\n /** Count of warning-severity diagnostics across all files. */\n readonly warningCount: number;\n /** Per-file reports, limited to files that produced at least one diagnostic. */\n readonly files: readonly FileReport[];\n}\n","import { neutralizeErb } from \"./erb\";\nimport {\n actionDescriptors,\n controllerIdentifiers,\n dasherize,\n isStimeoDataAttr,\n parseTargetAttr,\n parseValueAttr,\n} from \"./extract\";\nimport { type ElementNode, type ParsedAttr, parseHtml, walk } from \"./html_parser\";\nimport {\n type A11yAlternative,\n type A11yRequirement,\n DIAGNOSTIC_CODES,\n type Diagnostic,\n type DiagnosticCode,\n type DiagnosticFix,\n type DiagnosticSeverity,\n type Manifest,\n} from \"./types\";\n\n/**\n * The core Inspector engine: checks a single HTML/ERB source string against the\n * manifest and returns diagnostics. It is **input-path agnostic** — the same\n * function backs both the project's own contract checks and the user-facing CLI.\n *\n * The check runs in staged passes:\n * - **Stage 1 (names/spelling):** every `stimeo--*` controller, target, value,\n * and `data-action` controller **and method** must exist in the manifest.\n * - **Stage 2 (structure):** required targets must be present within their\n * controller scope, and targets must have an owning controller.\n * - **Stage 3 (accessibility):** ARIA the controller relies on but does not set\n * itself (e.g. a dialog's `role`/`aria-modal`/name) must be present on the\n * relevant target, with the expected value (alternative groups via `or`).\n * Three sibling passes extend it: **keyboard prerequisites** (declared\n * targets must be focusable), **managed-aria** (author-futile attributes the\n * controller owns draw warnings), and **idref resolution** (ARIA reference\n * attributes on scope/target elements must point at an id declared in the\n * same file — a *warning*, since a reference may legitimately cross a\n * partial boundary the checker cannot see).\n * - **Stage 4 (fix suggestions):** diagnostics carry a `suggestion` — the\n * nearest known name for a likely typo, or the exact ARIA to add.\n *\n * Any element may opt out via {@link IGNORE_ATTR} (`data-stimeo-ignore`): an\n * empty value suppresses every diagnostic anchored at the element or its\n * descendants; a whitespace-separated {@link DiagnosticCode} list narrows the\n * suppression to those codes. Unknown codes in the list are themselves\n * reported (`unknown-ignore-code`, never suppressible).\n *\n * @remarks\n * Scope is resolved within a single source string. A controller and its targets\n * split across separate Rails partials cannot be correlated, so stage-2 checks\n * assume self-contained markup (Stimeo's recommended demo/partial structure).\n * Server-rendered **fragments** — markup a controller fetches and appends at\n * runtime (Turbo Streams, incrementally loaded list pages) — are the\n * legitimate exception:\n * declare the runtime host with {@link FRAGMENT_ATTR} on the fragment root and\n * `orphan-target` is suppressed for that identifier (names are still checked).\n * ERB is neutralized first, so dynamically-generated attributes are skipped.\n *\n * @param source - Raw HTML/ERB source.\n * @param manifest - The bundled controller manifest to check against.\n * @returns Diagnostics sorted by line then column.\n */\nexport function checkSource(source: string, manifest: Manifest): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n const tree = parseHtml(neutralizeErb(source));\n const known = manifest.controllers;\n const knownIdentifiers = Object.keys(known);\n\n /** `[start, end)` offsets of every ERB tag in the raw source. */\n const erbRanges = [...source.matchAll(/<%[\\s\\S]*?%>/g)].map(\n (m) => [m.index ?? 0, (m.index ?? 0) + m[0].length] as const,\n );\n\n /**\n * Whether the attribute's value text was (even partially) ERB-generated.\n * Neutralization preserves offsets, so the parser's value range maps 1:1\n * onto the raw source.\n */\n const isDynamicValue = (attr: ParsedAttr): boolean => {\n const { valueStart, valueEnd } = attr;\n if (valueStart === undefined || valueEnd === undefined) return false;\n return erbRanges.some(([start, end]) => start < valueEnd && end > valueStart);\n };\n\n /** True when `node` or an ancestor opts out of `code` via the ignore attr. */\n const suppressed = (node: ElementNode, code: DiagnosticCode): boolean => {\n if (code === \"unknown-ignore-code\") return false; // meta-diagnostic: never suppressible\n let current: ElementNode | null = node;\n while (current && current.tag !== \"#root\") {\n const ignore = current.attrs.find((a) => a.name === IGNORE_ATTR);\n if (ignore) {\n const codes = ignore.value.trim();\n if (codes.length === 0 || codes.split(/\\s+/).includes(code)) return true;\n }\n current = current.parent;\n }\n return false;\n };\n\n /** Suppression-aware diagnostic sink; `owner` anchors the ignore lookup. */\n const report: Reporter = (owner, code, severity, message, at, suggestion, fix): void => {\n if (!suppressed(owner, code)) push(diagnostics, code, severity, message, at, suggestion, fix);\n };\n\n /** Controller scope registrations: a node declaring `data-controller`. */\n const scopes: Array<{ node: ElementNode; identifier: string }> = [];\n /** Target names found within each scope, keyed by scope node then identifier. */\n const presence = new Map<ElementNode, Map<string, Set<string>>>();\n /** Target *elements* per scope/identifier/target name, for stage-3 ARIA checks. */\n const targetNodes = new Map<ElementNode, Map<string, Map<string, ElementNode[]>>>();\n\n const recordPresence = (owner: ElementNode, identifier: string, target: string): void => {\n let byId = presence.get(owner);\n if (!byId) {\n byId = new Map();\n presence.set(owner, byId);\n }\n let set = byId.get(identifier);\n if (!set) {\n set = new Set();\n byId.set(identifier, set);\n }\n set.add(target);\n };\n\n const recordTargetNode = (\n owner: ElementNode,\n identifier: string,\n target: string,\n el: ElementNode,\n ): void => {\n let byId = targetNodes.get(owner);\n if (!byId) {\n byId = new Map();\n targetNodes.set(owner, byId);\n }\n let byName = byId.get(identifier);\n if (!byName) {\n byName = new Map();\n byId.set(identifier, byName);\n }\n const found = byName.get(target);\n if (found) found.push(el);\n else byName.set(target, [el]);\n };\n\n walk(tree, (node) => {\n for (const attr of node.attrs) {\n // --- suppression declaration: data-stimeo-ignore ---------------------\n if (attr.name === IGNORE_ATTR) {\n // Spell-check the code list so a typo'd suppression cannot silently\n // fail open. Reported directly: this meta-diagnostic is unsuppressible.\n for (const token of attr.value.split(/\\s+/).filter((t) => t.length > 0)) {\n if (!(DIAGNOSTIC_CODES as readonly string[]).includes(token)) {\n const best = nearestName(token, DIAGNOSTIC_CODES);\n push(\n diagnostics,\n \"unknown-ignore-code\",\n \"warning\",\n `Unknown diagnostic code \"${token}\" in ${IGNORE_ATTR}.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, token, best),\n );\n }\n }\n continue;\n }\n\n // --- fragment declaration: data-stimeo-fragment ----------------------\n if (attr.name === FRAGMENT_ATTR) {\n const identifiers = attr.value.split(/\\s+/).filter((token) => token.length > 0);\n if (identifiers.length === 0) {\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `\"${FRAGMENT_ATTR}\" must name the fragment's runtime host controller(s).`,\n attr,\n );\n }\n for (const identifier of identifiers) {\n if (!(identifier in known)) {\n const best = nearestName(identifier, knownIdentifiers);\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Fragment declaration references unknown Stimeo controller \"${identifier}\".`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, identifier, best),\n );\n }\n }\n continue;\n }\n\n // --- data-controller -------------------------------------------------\n if (attr.name === \"data-controller\") {\n for (const identifier of controllerIdentifiers(attr.value)) {\n if (identifier in known) {\n scopes.push({ node, identifier });\n } else {\n const best = nearestName(identifier, knownIdentifiers);\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Unknown Stimeo controller \"${identifier}\".`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, identifier, best),\n );\n }\n }\n continue;\n }\n\n // --- target attribute: data-{identifier}-target ----------------------\n const targetIdentifier = parseTargetAttr(attr.name);\n if (targetIdentifier) {\n const controller = known[targetIdentifier];\n if (!controller) {\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Target attribute \"${attr.name}\" references unknown Stimeo controller \"${targetIdentifier}\".`,\n attr,\n didYouMean(targetIdentifier, knownIdentifiers),\n );\n continue;\n }\n const targetName = attr.value.trim();\n if (targetName.length > 0 && !controller.targets.includes(targetName)) {\n const best = nearestName(targetName, controller.targets);\n report(\n node,\n \"unknown-target\",\n \"error\",\n `Unknown target \"${targetName}\" for \"${targetIdentifier}\". Known targets: ${list(controller.targets)}.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, targetName, best),\n );\n }\n const owner = findOwner(node, targetIdentifier);\n if (owner) {\n if (targetName.length > 0) {\n recordPresence(owner, targetIdentifier, targetName);\n recordTargetNode(owner, targetIdentifier, targetName, node);\n }\n } else if (!inDeclaredFragment(node, targetIdentifier)) {\n report(\n node,\n \"orphan-target\",\n \"error\",\n `Target \"${attr.name}\" has no enclosing controller \"${targetIdentifier}\".`,\n attr,\n );\n }\n continue;\n }\n\n // --- value attribute: data-{identifier}-{value}-value ----------------\n if (isStimeoDataAttr(attr.name) && attr.name.endsWith(\"-value\")) {\n const parsed = parseValueAttr(attr.name, knownIdentifiers);\n if (parsed) {\n if (parsed.identifier === null) {\n report(\n node,\n \"unknown-controller\",\n \"error\",\n `Value attribute \"${attr.name}\" references unknown Stimeo controller.`,\n attr,\n );\n } else {\n const controller = known[parsed.identifier];\n const valid =\n controller?.values.some((v) => dasherize(v) === parsed.valueToken) ?? false;\n if (!valid) {\n report(\n node,\n \"unknown-value\",\n \"error\",\n `Unknown value \"${parsed.valueToken}\" for \"${parsed.identifier}\". Known values: ${list((controller?.values ?? []).map(dasherize))}.`,\n attr,\n didYouMean(parsed.valueToken, (controller?.values ?? []).map(dasherize)),\n );\n }\n }\n continue;\n }\n }\n\n // --- data-action descriptors: controller + method --------------------\n if (attr.name === \"data-action\") {\n for (const { identifier, method } of actionDescriptors(attr.value)) {\n const controller = known[identifier];\n if (!controller) {\n const best = nearestName(identifier, knownIdentifiers);\n report(\n node,\n \"unknown-action-controller\",\n \"error\",\n `Action references unknown Stimeo controller \"${identifier}\".`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, identifier, best),\n );\n } else if (method.length > 0 && !controller.actions.includes(method)) {\n const best = nearestName(method, controller.actions);\n report(\n node,\n \"unknown-action-method\",\n \"error\",\n `Unknown action \"${method}\" for \"${identifier}\". Known actions: ${list(controller.actions)}.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, method, best),\n );\n }\n }\n }\n }\n });\n\n // --- Stage 2: required targets per scope ---------------------------------\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n const present = presence.get(node)?.get(identifier) ?? new Set<string>();\n for (const required of controller.requiredTargets) {\n if (!present.has(required)) {\n report(\n node,\n \"missing-required-target\",\n \"error\",\n `\"${identifier}\" is missing required target \"${required}\".`,\n node,\n );\n }\n }\n }\n\n // --- Stage 3: accessibility (ARIA) per scope -----------------------------\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const req of controller.a11y) {\n // The root scope (\"\") is the controller element; otherwise the target's\n // own element(s). Targets that are absent are stage 2's concern, not ours\n // — we only judge accessibility of markup that is actually present.\n const elements =\n req.target === \"\"\n ? [node]\n : (targetNodes.get(node)?.get(identifier)?.get(req.target) ?? []);\n for (const el of elements) {\n checkA11y(report, el, identifier, req);\n }\n }\n }\n\n // --- Stage 3: keyboard prerequisites per scope ---------------------------\n // Declared targets whose contract makes the author responsible for\n // focusability must be natively focusable or carry tabindex/contenteditable.\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const req of controller.keyboard) {\n const reach = req.reach ?? \"tab\";\n const elements = targetNodes.get(node)?.get(identifier)?.get(req.target) ?? [];\n for (const el of elements) {\n if (!isFocusable(el, reach)) {\n const problem =\n reach === \"tab\"\n ? 'not in the Tab order (needs a native control or tabindex=\"0\")'\n : \"not focusable (needs a native control or tabindex)\";\n report(\n el,\n \"keyboard-inaccessible\",\n \"error\",\n `The \"${req.target}\" target of \"${identifier}\" is ${problem}.`,\n el,\n req.suggestion,\n );\n }\n }\n }\n }\n\n // --- Stage 3: author-futile (controller-managed) attributes --------------\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const rule of controller.managedAria) {\n const elements =\n rule.target === \"\"\n ? [node]\n : (targetNodes.get(node)?.get(identifier)?.get(rule.target) ?? []);\n const where = rule.target === \"\" ? \"scope element\" : `\"${rule.target}\" target`;\n for (const el of elements) {\n for (const name of rule.attrs) {\n const attr = el.attrs.find((a) => a.name === name);\n if (!attr) continue;\n report(\n el,\n \"managed-aria\",\n \"warning\",\n `${name} on the ${where} of \"${identifier}\" is managed by the controller at runtime.`,\n attr,\n rule.suggestion,\n );\n }\n }\n }\n }\n\n // --- Stage 3: cross-controller composition values ------------------------\n // Value-alignment contracts between a host controller and a co-located\n // companion (e.g. sortable's sort axis vs roving's orientation). Both sides\n // are judged by their *effective* value — the authored attribute, or the\n // rule's declared default when absent — because these contracts exist\n // precisely where the companion's default does not match the host's. An\n // ERB-generated value on either side makes the rule undecidable, so it is\n // skipped rather than guessed at.\n for (const { node, identifier } of scopes) {\n const controller = known[identifier];\n if (!controller) continue;\n for (const rule of controller.compositions) {\n const targeted = targetNodes.get(node)?.get(identifier)?.get(rule.target);\n // An absent optional container target falls back to the scope element\n // when the rule says the runtime does the same (e.g. sortable's `list`).\n const elements =\n rule.target === \"\" ? [node] : (targeted ?? (rule.fallbackToScope ? [node] : []));\n const where = rule.target === \"\" || !targeted ? \"scope element\" : `\"${rule.target}\" target`;\n const when = rule.when;\n if (when) {\n const hostAttr = node.attrs.find(\n (a) => a.name === `data-${identifier}-${dasherize(when.value)}-value`,\n );\n if (hostAttr && isDynamicValue(hostAttr)) continue;\n const hostEffective = hostAttr ? hostAttr.value.trim() : when.default;\n if (!when.equals.includes(hostEffective)) continue;\n }\n const hostContext = when ? ` (${when.value} ${list(when.equals)})` : \"\";\n for (const el of elements) {\n const declared = el.attrs.find((a) => a.name === \"data-controller\");\n if (!declared || !controllerIdentifiers(declared.value).includes(rule.coController)) {\n continue;\n }\n const coAttrName = `data-${rule.coController}-${dasherize(rule.require.value)}-value`;\n const coAttr = el.attrs.find((a) => a.name === coAttrName);\n if (coAttr && isDynamicValue(coAttr)) continue;\n const effective = coAttr ? coAttr.value.trim() : rule.require.default;\n if (rule.require.oneOf.includes(effective)) continue;\n const [canonical] = rule.require.oneOf;\n if (!coAttr) {\n report(\n el,\n \"composition-mismatch\",\n \"error\",\n `\"${identifier}\"${hostContext} requires the co-located \"${rule.coController}\" on its ${where} to set ${coAttrName} to ${list(rule.require.oneOf)} (its default is \"${rule.require.default}\").`,\n el,\n rule.suggestion,\n );\n } else {\n report(\n el,\n \"composition-mismatch\",\n \"error\",\n `${coAttrName}=\"${coAttr.value}\" on the ${where} of \"${identifier}\"${hostContext} must be ${list(rule.require.oneOf)}.`,\n coAttr,\n rule.suggestion,\n canonical !== undefined\n ? valueFix(coAttr, canonical, `Set ${coAttrName} to \"${canonical}\"`)\n : undefined,\n );\n }\n }\n }\n }\n\n // --- Stage 3: ARIA idref resolution --------------------------------------\n // Scope/target elements are where the rules above push authors to write\n // reference attributes; a token that resolves to no id in the same file is\n // (at best) split across partials and (at worst) a typo that silently\n // empties an accessible name. Warning severity: only this file is visible.\n const ids = new Set<string>();\n walk(tree, (node) => {\n const id = node.attrs.find((a) => a.name === \"id\");\n if (!id || isDynamicValue(id)) return;\n const value = id.value.trim();\n if (value.length > 0 && !/\\s/.test(value)) ids.add(value);\n });\n\n const anchored = new Set<ElementNode>(scopes.map((scope) => scope.node));\n for (const byIdentifier of targetNodes.values()) {\n for (const byName of byIdentifier.values()) {\n for (const els of byName.values()) {\n for (const el of els) anchored.add(el);\n }\n }\n }\n for (const el of anchored) {\n for (const attr of el.attrs) {\n if (!IDREF_ATTRS.has(attr.name) || isDynamicValue(attr)) continue;\n for (const token of attr.value.split(/\\s+/).filter((t) => t.length > 0)) {\n if (!ids.has(token)) {\n const best = nearestName(token, [...ids]);\n report(\n el,\n \"unresolved-idref\",\n \"warning\",\n `${attr.name} references id \"${token}\", but no element in this file declares it.`,\n attr,\n asDidYouMean(best),\n tokenFix(attr, token, best),\n );\n }\n }\n }\n }\n\n diagnostics.sort((a, b) => a.line - b.line || a.column - b.column);\n return diagnostics;\n}\n\n/**\n * Where a diagnostic is anchored in the source: an attribute (position of the\n * attribute name) or an element (position of the tag's `<`). Knowing which of\n * the two it is lets {@link push} derive the anchored token's length.\n */\ntype Anchor = ParsedAttr | ElementNode;\n\n/** Suppression-aware diagnostic sink bound to a source's ignore declarations. */\ntype Reporter = (\n owner: ElementNode,\n code: DiagnosticCode,\n severity: DiagnosticSeverity,\n message: string,\n at: Anchor,\n suggestion?: string,\n fix?: DiagnosticFix,\n) => void;\n\n/**\n * Checks one accessibility requirement against a present element. The base\n * `attrs`/`values` pair and each `or` alternative are alternatives (OR): the\n * requirement is met when at least one candidate attribute is present.\n *\n * Value checking is resolved **per attribute name** by unioning the allowed\n * values across every group that lists that name — so a value valid in *any*\n * of its groups is accepted (a group without `values` accepts anything). This\n * matters when the same attribute appears in more than one group: a value\n * that is valid in one group must not be flagged just because another group\n * lists a different set. Distinct attributes still stand alone, so an authored\n * `aria-live=\"off\"` is flagged even next to a valid `role=\"status\"`.\n */\nfunction checkA11y(\n report: Reporter,\n el: ElementNode,\n identifier: string,\n req: A11yRequirement,\n): void {\n const groups: readonly A11yAlternative[] = [\n { attrs: req.attrs, values: req.values },\n ...(req.or ?? []),\n ];\n const where = req.target === \"\" ? \"scope element\" : `\"${req.target}\" target`;\n\n // Per attribute name: the union of allowed values across the groups that\n // list it (`anyValue` when some group leaves the value unconstrained).\n const allowedByAttr = new Map<string, { anyValue: boolean; values: Set<string> }>();\n for (const group of groups) {\n for (const name of group.attrs) {\n let entry = allowedByAttr.get(name);\n if (!entry) {\n entry = { anyValue: false, values: new Set() };\n allowedByAttr.set(name, entry);\n }\n if (!group.values) entry.anyValue = true;\n else for (const value of group.values) entry.values.add(value);\n }\n }\n\n const invalid: Array<{ attr: ParsedAttr; values: readonly string[] }> = [];\n let anyPresent = false;\n for (const [name, allowed] of allowedByAttr) {\n const attr = el.attrs.find((a) => a.name === name);\n if (!attr) continue;\n anyPresent = true;\n if (!allowed.anyValue && !allowed.values.has(attr.value.trim())) {\n invalid.push({ attr, values: [...allowed.values] });\n }\n }\n\n if (!anyPresent) {\n report(\n el,\n \"missing-aria\",\n \"error\",\n `\"${identifier}\" requires ${describeAttrs([...allowedByAttr.keys()])} on its ${where}.`,\n el,\n req.suggestion,\n );\n return;\n }\n for (const { attr, values } of invalid) {\n // The attribute exists but holds a wrong value, so the rule's \"Add …\"\n // suggestion would mislead — point at the value fix instead. When exactly\n // one value is allowed the correction is unambiguous, so emit it as a\n // machine fix too; multi-valued rules stay a human decision.\n const [only] = values;\n report(\n el,\n \"invalid-aria-value\",\n \"error\",\n `${attr.name}=\"${attr.value}\" is not valid on the ${where} of \"${identifier}\". Expected ${list(values)}.`,\n attr,\n `Set ${attr.name} to ${list(values)}.`,\n values.length === 1 && only !== undefined\n ? valueFix(attr, only, `Set ${attr.name} to \"${only}\"`)\n : undefined,\n );\n }\n}\n\n/** Tags focusable without an authored `tabindex` (input handled separately). */\nconst NATIVE_FOCUSABLE_TAGS = new Set([\"button\", \"select\", \"textarea\", \"summary\"]);\n\n/**\n * Whether the tag is natively focusable **as authored**. `input` is focusable\n * *unless* `type=\"hidden\"` (never rendered, never focusable); `a`/`area` are\n * focusable only with an `href`. Deliberately does **not** consider `disabled`,\n * `hidden`, or `inert`: those are usually intentional states, and — crucially —\n * this library's roving contracts keep items inside an ancestor-`hidden`\n * container until opened (a closed `<ul role=\"menu\" hidden>`), so treating them\n * as non-focusable would false-positive on every correct menu.\n */\nfunction isNativelyFocusable(el: ElementNode): boolean {\n if (NATIVE_FOCUSABLE_TAGS.has(el.tag)) return true;\n if (el.tag === \"input\") {\n const type = (el.attrs.find((a) => a.name === \"type\")?.value ?? \"\").trim().toLowerCase();\n return type !== \"hidden\";\n }\n if (el.tag === \"a\" || el.tag === \"area\") return el.attrs.some((a) => a.name === \"href\");\n return false;\n}\n\n/** Parsed integer `tabindex`, or `null` when absent or not a valid integer. */\nfunction tabindexValue(el: ElementNode): number | null {\n const attr = el.attrs.find((a) => a.name === \"tabindex\");\n if (!attr) return null;\n const parsed = Number.parseInt(attr.value.trim(), 10);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\n/**\n * Static focusability floor for the keyboard-prerequisite pass, per the rule's\n * {@link KeyboardRequirement.reach}:\n *\n * - `\"tab\"`: the element must be in the Tab order — natively focusable /\n * `contenteditable` with no `tabindex`, or `tabindex >= 0`. A `tabindex=\"-1\"`\n * (or a present-but-invalid value) fails, catching the \"removed from Tab\n * order\" bug a presence-only check would miss.\n * - `\"focus\"`: the controller focuses it programmatically, so any valid\n * `tabindex` (including the roving `-1`), a natively focusable element, or\n * `contenteditable` suffices.\n *\n * Presence-only otherwise — the set-level roving invariant is runtime state.\n */\nfunction isFocusable(el: ElementNode, reach: \"tab\" | \"focus\"): boolean {\n const hasTabindex = el.attrs.some((a) => a.name === \"tabindex\");\n if (hasTabindex) {\n const value = tabindexValue(el);\n if (value === null) return false; // present but invalid → not reliably focusable\n return reach === \"tab\" ? value >= 0 : true;\n }\n return isNativelyFocusable(el) || isContentEditable(el);\n}\n\n/**\n * Whether `contenteditable` makes the element focusable. Bare `contenteditable`\n * / `=\"true\"` / `=\"plaintext-only\"` are editable (focusable); only the explicit\n * `=\"false\"` opts out, so it must not count as focusable.\n */\nfunction isContentEditable(el: ElementNode): boolean {\n const attr = el.attrs.find((a) => a.name === \"contenteditable\");\n return attr !== undefined && attr.value.trim().toLowerCase() !== \"false\";\n}\n\n/**\n * ARIA attributes whose value is an idref (list); the idref-resolution pass\n * checks each token against the ids declared in the same file.\n */\nconst IDREF_ATTRS = new Set([\n \"aria-activedescendant\",\n \"aria-controls\",\n \"aria-describedby\",\n \"aria-details\",\n \"aria-errormessage\",\n \"aria-flowto\",\n \"aria-labelledby\",\n \"aria-owns\",\n]);\n\n/**\n * Opts an element (and its subtree) out of diagnostics: an empty value\n * suppresses everything, a whitespace-separated {@link DiagnosticCode} list\n * suppresses exactly those codes. The escape hatch for the rare markup the\n * static rules cannot see well enough (a reference resolved in another\n * partial, an intentionally exotic composition) — each use is greppable and\n * reviewable. Single-dash namespace like {@link FRAGMENT_ATTR}, so it can\n * never collide with a controller's own attribute namespace.\n */\nconst IGNORE_ATTR = \"data-stimeo-ignore\";\n\n/** Climbs the ancestor chain (including `node`) for the nearest owning scope. */\nfunction findOwner(node: ElementNode, identifier: string): ElementNode | null {\n let current: ElementNode | null = node;\n while (current && current.tag !== \"#root\") {\n const dataController = current.attrs.find((a) => a.name === \"data-controller\");\n if (dataController && controllerIdentifiers(dataController.value).includes(identifier)) {\n return current;\n }\n current = current.parent;\n }\n return null;\n}\n\n/**\n * Declares a server-rendered **fragment**: markup a controller fetches and\n * appends at runtime inside its own scope (a Turbo Stream template, an\n * incrementally fetched page of list items). Its value is the runtime host —\n * whitespace-separated `stimeo--*` identifiers. Targets inside the declaration\n * are exempt from `orphan-target` for exactly those identifiers; every name is\n * still spell-checked against the manifest, including the declaration itself.\n * Deliberately single-dash (`data-stimeo-`, not `data-stimeo--`) so it can never\n * collide with a controller's own `data-stimeo--<id>-*` attribute namespace.\n */\nconst FRAGMENT_ATTR = \"data-stimeo-fragment\";\n\n/** Whether `node` (or an ancestor) declares itself a fragment of `identifier`. */\nfunction inDeclaredFragment(node: ElementNode, identifier: string): boolean {\n let current: ElementNode | null = node;\n while (current && current.tag !== \"#root\") {\n const declared = current.attrs.find((a) => a.name === FRAGMENT_ATTR);\n if (declared?.value.split(/\\s+/).includes(identifier)) return true;\n current = current.parent;\n }\n return false;\n}\n\n/**\n * Length of the token an anchor points at: the attribute name, or the opening\n * `<tag` (the `<` plus the tag name) for element anchors.\n */\nfunction anchorLength(at: Anchor): number {\n return \"name\" in at ? at.name.length : at.tag.length + 1;\n}\n\n/** Appends a diagnostic positioned at the given source location. */\nfunction push(\n out: Diagnostic[],\n code: DiagnosticCode,\n severity: DiagnosticSeverity,\n message: string,\n at: Anchor,\n suggestion?: string,\n fix?: DiagnosticFix,\n): void {\n out.push({\n code,\n severity,\n message,\n line: at.line,\n column: at.column,\n length: anchorLength(at),\n suggestion,\n fix,\n });\n}\n\n/**\n * Machine fix replacing one occurrence of `token` inside the attribute's\n * value with `replacement`. Returns undefined when there is no replacement,\n * the attribute is boolean (no value offsets), or the token cannot be located\n * verbatim. Uses the first occurrence — a value repeating the same broken\n * token is pathological enough that fixing the first is still the right edit.\n */\nfunction tokenFix(\n attr: ParsedAttr,\n token: string,\n replacement: string | undefined,\n): DiagnosticFix | undefined {\n if (replacement === undefined || attr.valueStart === undefined || token.length === 0) {\n return undefined;\n }\n const index = attr.value.indexOf(token);\n if (index < 0) return undefined;\n const start = attr.valueStart + index;\n return {\n start,\n end: start + token.length,\n text: replacement,\n title: `Replace with \"${replacement}\"`,\n };\n}\n\n/** Machine fix replacing the attribute's entire value. */\nfunction valueFix(attr: ParsedAttr, replacement: string, title: string): DiagnosticFix | undefined {\n if (attr.valueStart === undefined || attr.valueEnd === undefined) return undefined;\n return { start: attr.valueStart, end: attr.valueEnd, text: replacement, title };\n}\n\n/** Formats a name list for human-readable messages. */\nfunction list(names: readonly string[]): string {\n return names.length > 0 ? names.map((n) => `\"${n}\"`).join(\", \") : \"(none)\";\n}\n\n/** Describes a set of \"any of\" attributes, e.g. `aria-labelledby or aria-label`. */\nfunction describeAttrs(attrs: readonly string[]): string {\n return attrs.length === 1 ? (attrs[0] as string) : attrs.join(\" or \");\n}\n\n/**\n * Stage-4 typo candidate: the nearest known name when it is close enough to\n * be a plausible misspelling, else undefined. The threshold scales with name\n * length but is capped, so unrelated names never produce a misleading match.\n * Feeds both the human suggestion ({@link didYouMean}) and the machine fix.\n */\nfunction nearestName(name: string, candidates: readonly string[]): string | undefined {\n if (name.length === 0) return undefined;\n let best: string | undefined;\n let bestDistance = Number.POSITIVE_INFINITY;\n for (const candidate of candidates) {\n const distance = levenshtein(name, candidate);\n if (distance < bestDistance) {\n bestDistance = distance;\n best = candidate;\n }\n }\n const threshold = Math.min(3, Math.floor(name.length / 2) + 1);\n return best !== undefined && bestDistance <= threshold ? best : undefined;\n}\n\n/** Formats a {@link nearestName} candidate as the human-readable suggestion. */\nfunction asDidYouMean(best: string | undefined): string | undefined {\n return best === undefined ? undefined : `Did you mean \"${best}\"?`;\n}\n\n/**\n * Stage-4 typo suggestion: `Did you mean \"x\"?`, or undefined when nothing is\n * close. Exported for the MCP server's `stimeo_controller` unknown-id hint.\n */\nexport function didYouMean(name: string, candidates: readonly string[]): string | undefined {\n return asDidYouMean(nearestName(name, candidates));\n}\n\n/** Classic dynamic-programming Levenshtein edit distance. */\nfunction levenshtein(a: string, b: string): number {\n const rows = a.length;\n const cols = b.length;\n if (rows === 0) return cols;\n if (cols === 0) return rows;\n let prev = Array.from({ length: cols + 1 }, (_, j) => j);\n for (let i = 1; i <= rows; i++) {\n const curr = [i];\n for (let j = 1; j <= cols; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n (curr[j - 1] as number) + 1,\n (prev[j] as number) + 1,\n (prev[j - 1] as number) + cost,\n );\n }\n prev = curr;\n }\n return prev[cols] as number;\n}\n","import { checkSource } from \"./check\";\nimport type { Manifest } from \"./types\";\n\n/**\n * Bundled example index for the MCP server (`stimeo_example` tool and\n * `stimeo://examples/*` resources).\n *\n * The examples are the official catalog's demo sidecars — the exact markup\n * shown verbatim in each demo's code tab and copy-pasted by users, so they\n * are the closest thing the project has to \"verified reference markup\".\n * `scripts/postbuild.ts` walks them at build time (`scripts/demo_sources.ts`\n * resolves the supply: the playground catalog in the dev monorepo,\n * `examples/` in the public mirror) and serializes the result of\n * {@link buildExamplesIndex} into `dist/inspector/examples.json`, next to\n * `manifest.json`.\n *\n * {@link buildExamplesIndex} is pure so the mapping and the verification gate\n * are unit-tested directly; the filesystem walk stays in the build scripts.\n */\n\n/** Format version of `examples.json` (bumped on breaking shape changes). */\nexport const EXAMPLES_SCHEMA_VERSION = 1;\n\n/** One bundled example: the demo markup shown verbatim in the catalog. */\nexport interface ExampleEntry {\n /**\n * Repo-relative provenance: `playground/.../demos/menu/_demo.html.erb` in\n * the dev monorepo, `examples/menu/_demo.html.erb` in the public mirror.\n */\n readonly file: string;\n /** The HTML/ERB source. */\n readonly source: string;\n}\n\n/** The bundled `examples.json`: verified demo markup keyed by controller id. */\nexport interface ExamplesIndex {\n readonly schemaVersion: number;\n /** Keyed by controller identifier, e.g. `stimeo--menu`. Keys are sorted. */\n readonly examples: Readonly<Record<string, ExampleEntry>>;\n}\n\n/** One demo sidecar as discovered on disk by the build script. */\nexport interface DemoSource {\n /** Demo directory basename (snake_case), e.g. `inline_combobox`. */\n readonly dir: string;\n /** Repo-relative path of the `_demo.html.erb` file. */\n readonly file: string;\n /** The file's contents. */\n readonly source: string;\n}\n\n/**\n * Maps a demo directory basename to its controller identifier. Demo dirs use\n * snake_case (`date_range_picker`); controller identifiers are the `stimeo--`\n * prefix plus the kebab-case name (`stimeo--date-range-picker`).\n * {@link buildExamplesIndex} enforces a 1:1 mapping between the demos tree and\n * the manifest.\n */\nexport function demoDirToControllerId(dir: string): string {\n return `stimeo--${dir.replaceAll(\"_\", \"-\")}`;\n}\n\n/**\n * Controllers temporarily exempted from the demo/manifest bijection. The\n * reverse check fails when an exempted controller gains a demo, so every entry\n * must be removed as soon as its exemption is no longer needed.\n */\nexport const PENDING_DEMO_CONTROLLERS: ReadonlySet<string> = new Set([]);\n\n/**\n * Builds the bundled example index from the discovered demo sidecars,\n * enforcing two invariants so \"verified example\" stays true:\n *\n * 1. **Bijection with the manifest.** Every demo dir must map to a known\n * controller and every controller must have a demo — a mismatch on either\n * side means the catalog and the library drifted, and the build must fail\n * loudly rather than silently ship a hole. The only exception is the\n * explicit `pendingDemos` allowlist ({@link PENDING_DEMO_CONTROLLERS}):\n * a documented \"demo not built yet\" deferral, kept honest by the reverse\n * check (an allowlisted controller acquiring a demo fails the build until\n * the stale entry is removed).\n * 2. **Check-clean.** Every example must pass {@link checkSource} with no\n * error-severity diagnostics against the same manifest it ships with.\n *\n * @throws Error listing every violation when an invariant is broken.\n */\nexport function buildExamplesIndex(\n demos: readonly DemoSource[],\n manifest: Manifest,\n pendingDemos: ReadonlySet<string> = PENDING_DEMO_CONTROLLERS,\n): ExamplesIndex {\n const problems: string[] = [];\n const byId = new Map<string, DemoSource>();\n for (const demo of demos) {\n const id = demoDirToControllerId(demo.dir);\n if (!Object.hasOwn(manifest.controllers, id)) {\n problems.push(`demo \"${demo.dir}\" maps to unknown controller \"${id}\"`);\n continue;\n }\n if (byId.has(id)) {\n problems.push(`controller \"${id}\" has more than one demo source`);\n continue;\n }\n byId.set(id, demo);\n }\n for (const id of Object.keys(manifest.controllers)) {\n if (byId.has(id) || pendingDemos.has(id)) continue;\n problems.push(`controller \"${id}\" has no demo example`);\n }\n for (const id of pendingDemos) {\n if (byId.has(id)) {\n problems.push(\n `controller \"${id}\" is allowlisted as pending but now has a demo — ` +\n \"remove it from PENDING_DEMO_CONTROLLERS\",\n );\n }\n }\n for (const [id, demo] of byId) {\n const errors = checkSource(demo.source, manifest).filter((d) => d.severity === \"error\");\n for (const d of errors) {\n problems.push(`example for \"${id}\" fails check: ${d.line}:${d.column} ${d.message}`);\n }\n }\n if (problems.length > 0) {\n throw new Error(`examples index build failed:\\n - ${problems.join(\"\\n - \")}`);\n }\n // Null-prototype dictionary, mirroring runCatalogTool: ids derive from\n // directory names, and a hostile \"__proto__\" would otherwise rewrite the\n // dictionary's prototype instead of storing the entry.\n const examples: Record<string, ExampleEntry> = Object.create(null);\n for (const id of [...byId.keys()].sort()) {\n const demo = byId.get(id);\n if (!demo) continue;\n examples[id] = { file: demo.file, source: demo.source };\n }\n return { schemaVersion: EXAMPLES_SCHEMA_VERSION, examples };\n}\n","import { extname } from \"node:path\";\n\n/**\n * Single source of truth for which files the Inspector checks. Shared by the\n * CLI's directory walk and the VS Code extension's document filter so a file\n * never gets diagnostics in one surface and a silent pass in the other.\n */\n\n/** Final extensions (lowercased) the Inspector understands. `.html.erb` ends with `.erb`. */\nconst CHECKABLE_FILE_EXTENSIONS = new Set([\".erb\", \".html\", \".htm\"]);\n\n/**\n * Whether the path names a checkable HTML/ERB file. Matches on the *final*\n * extension only (`extname`), case-insensitively — case-only variants like\n * `legacy.HTM` are the same file on the case-insensitive filesystems most\n * Rails apps are edited on (macOS/Windows), so they must not slip past CI\n * while the editor flags them.\n */\nexport function isCheckableFile(path: string): boolean {\n return CHECKABLE_FILE_EXTENSIONS.has(extname(path).toLowerCase());\n}\n","import { readFileSync } from \"node:fs\";\nimport type { Manifest } from \"./types\";\n\n/**\n * Loading and shape-validation of `manifest.json` files, shared by every\n * consumer that reads a manifest from disk: the CLI (the copy bundled next to\n * `cli_bin.js`), the VS Code extension (a workspace's installed copy or its\n * bundled snapshot), and any future server (MCP) doing the same. Keeping the\n * guard in one place means a corrupt or cross-version manifest degrades the\n * same way everywhere instead of crashing one surface and passing another.\n */\n\n/** Array-typed fields the schema-v5 engine iterates on every controller entry. */\nconst CONTROLLER_ARRAY_FIELDS = [\n \"targets\",\n \"values\",\n \"actions\",\n \"events\",\n \"requiredTargets\",\n \"a11y\",\n \"keyboard\",\n \"managedAria\",\n \"compositions\",\n] as const;\n\n/**\n * Structural guard for a parsed manifest. A reader bundles the engine of one\n * schema version but may load a manifest written by another (e.g. an app\n * installing a package whose manifest predates `keyboard`/`managedAria`), and\n * the engine iterates those arrays unconditionally — an unvalidated manifest\n * would crash every check instead of failing cleanly. Shape-based rather than\n * a strict `schemaVersion` equality so additive future versions keep working.\n */\nexport function isCompatibleManifest(value: unknown): value is Manifest {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n if (typeof record.schemaVersion !== \"number\" || typeof record.packageVersion !== \"string\") {\n return false;\n }\n const controllers = record.controllers;\n if (typeof controllers !== \"object\" || controllers === null || Array.isArray(controllers)) {\n return false;\n }\n for (const entry of Object.values(controllers as Record<string, unknown>)) {\n if (typeof entry !== \"object\" || entry === null) return false;\n for (const field of CONTROLLER_ARRAY_FIELDS) {\n if (!Array.isArray((entry as Record<string, unknown>)[field])) return false;\n }\n }\n return true;\n}\n\n/**\n * Reads and parses one manifest file; throws on missing/corrupt files and on\n * manifests whose shape the bundled engine cannot consume.\n */\nexport function readManifestFile(path: string): Manifest {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n if (!isCompatibleManifest(parsed)) {\n throw new Error(`Incompatible or malformed manifest: ${path}`);\n }\n return parsed;\n}\n","import { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\nimport { checkSource } from \"./check\";\nimport type { ExamplesIndex } from \"./examples\";\nimport { EXAMPLES_SCHEMA_VERSION } from \"./examples\";\nimport { isCheckableFile } from \"./files\";\nimport { readManifestFile } from \"./manifest_io\";\nimport type { CheckReport, ControllerManifest, Diagnostic, FileReport, Manifest } from \"./types\";\n\n/**\n * `stimeo check <path...>` / `stimeo catalog` — static checker and catalog\n * for `stimeo--*` markup.\n *\n * This is the executable entry point bundled as the `stimeo` npm bin. It is a\n * thin shell around {@link checkSource} and the bundled manifest: discover\n * files, run the engine, format the report, and set the exit code. All checking\n * logic lives in the engine so the CLI and the project's own checks use exactly the same\n * code path. Both commands accept `--json` to emit machine-readable output for\n * editor tooling and CI.\n */\n\n/** Resolves one of the JSON artifacts postbuild writes next to this file in `dist/inspector/`. */\nfunction bundledPath(name: string): string {\n return join(dirname(fileURLToPath(import.meta.url)), name);\n}\n\n/**\n * Loads the manifest bundled next to this file (`dist/inspector/manifest.json`),\n * shape-validated so a corrupt build artifact fails loudly here rather than as\n * an engine crash mid-check. Exported for the MCP server (`stimeo mcp`), which\n * loads the same bundled manifest at startup.\n */\nexport function loadManifest(): Manifest {\n return readManifestFile(bundledPath(\"manifest.json\"));\n}\n\n/**\n * Loads the example index bundled next to this file\n * (`dist/inspector/examples.json`), rejecting a format-version mismatch: the\n * index is only ever read by the build it shipped with, so a mismatch means a\n * corrupted or mixed installation and must fail loudly, not misbehave.\n */\nexport function loadExamplesIndex(): ExamplesIndex {\n const index = JSON.parse(readFileSync(bundledPath(\"examples.json\"), \"utf8\")) as ExamplesIndex;\n if (index.schemaVersion !== EXAMPLES_SCHEMA_VERSION) {\n throw new Error(\n `examples.json schema version ${index.schemaVersion} does not match this build ` +\n `(expected ${EXAMPLES_SCHEMA_VERSION}); reinstall or rebuild the package.`,\n );\n }\n return index;\n}\n\n/** Recursively collects checkable files under the given path. */\nfunction collectFiles(target: string, out: string[]): void {\n const stat = statSync(target);\n if (stat.isDirectory()) {\n for (const entry of readdirSync(target)) {\n collectFiles(join(target, entry), out);\n }\n return;\n }\n if (isCheckableFile(target)) out.push(target);\n}\n\n/** Builds a report for a single file. */\nfunction checkFile(file: string, manifest: Manifest): FileReport {\n const source = readFileSync(file, \"utf8\");\n return { file, diagnostics: checkSource(source, manifest) };\n}\n\n/**\n * Formats one diagnostic, e.g. ` 13:5 error message [code]`. A stage-4\n * suggestion, when present, is appended on its own indented `→` line.\n */\nfunction formatDiagnostic(d: Diagnostic): string {\n const where = `${d.line}:${d.column}`.padEnd(7);\n const head = ` ${where} ${d.severity.padEnd(7)} ${d.message} [${d.code}]`;\n return d.suggestion ? `${head}\\n → ${d.suggestion}` : head;\n}\n\n/**\n * Escapes workflow-command *message* data (`%`, CR, LF) per the GitHub Actions\n * toolkit's escaping rules.\n */\nfunction escapeGithubData(value: string): string {\n return value.replaceAll(\"%\", \"%25\").replaceAll(\"\\r\", \"%0D\").replaceAll(\"\\n\", \"%0A\");\n}\n\n/** Escapes a workflow-command *property* value (message rules plus `:`, `,`). */\nfunction escapeGithubProperty(value: string): string {\n return escapeGithubData(value).replaceAll(\":\", \"%3A\").replaceAll(\",\", \"%2C\");\n}\n\n/**\n * Formats one diagnostic as a GitHub Actions workflow command\n * (`::error file=…,line=…,col=…,title=…::message`). Emitting these from any CI\n * step makes the runner render inline annotations on the PR diff — no\n * marketplace action, upload step, or SARIF pipeline required.\n */\nexport function formatGithubAnnotation(file: string, d: Diagnostic): string {\n const properties = [\n `file=${escapeGithubProperty(file)}`,\n `line=${d.line}`,\n `col=${d.column}`,\n `title=${escapeGithubProperty(`Stimeo Inspector [${d.code}]`)}`,\n ].join(\",\");\n const message = d.suggestion ? `${d.message} → ${d.suggestion}` : d.message;\n return `::${d.severity} ${properties}::${escapeGithubData(message)}`;\n}\n\n/**\n * Aggregates per-file reports into the structured {@link CheckReport}, keeping\n * only files that produced diagnostics and tallying severities. Pure (no I/O),\n * so the JSON output contract is unit-tested directly.\n */\nexport function buildCheckReport(\n reports: readonly FileReport[],\n checkedFiles: number,\n): CheckReport {\n let errorCount = 0;\n let warningCount = 0;\n const files: FileReport[] = [];\n for (const report of reports) {\n if (report.diagnostics.length === 0) continue;\n files.push(report);\n for (const d of report.diagnostics) {\n if (d.severity === \"error\") errorCount++;\n else warningCount++;\n }\n }\n return { ok: errorCount === 0, checkedFiles, errorCount, warningCount, files };\n}\n\n/**\n * Controller entries sorted by identifier — the canonical iteration order for\n * catalog-style output. Shared by the CLI summary below and the MCP\n * `stimeo_catalog` tool so both render the manifest in the same order.\n */\nexport function sortedControllerEntries(\n manifest: Manifest,\n): ReadonlyArray<readonly [string, ControllerManifest]> {\n return Object.keys(manifest.controllers)\n .sort()\n .flatMap((id) => {\n const controller = manifest.controllers[id];\n return controller ? [[id, controller] as const] : [];\n });\n}\n\n/**\n * Renders the manifest as a human-readable catalog: one block per controller\n * listing its non-empty target/value/action/event names. `--json` emits the\n * raw manifest instead, for machine consumption.\n */\nexport function catalogSummary(manifest: Manifest): string[] {\n const entries = sortedControllerEntries(manifest);\n const lines = [\n `Stimeo UI catalog — ${entries.length} controller(s) (schema v${manifest.schemaVersion}, package ${manifest.packageVersion})`,\n \"\",\n ];\n for (const [id, c] of entries) {\n lines.push(id);\n if (c.targets.length > 0) lines.push(` targets: ${c.targets.join(\", \")}`);\n if (c.values.length > 0) lines.push(` values: ${c.values.join(\", \")}`);\n if (c.actions.length > 0) lines.push(` actions: ${c.actions.join(\", \")}`);\n if (c.events.length > 0) lines.push(` events: ${c.events.join(\", \")}`);\n }\n return lines;\n}\n\nconst USAGE = `stimeo — static checker and catalog for Stimeo UI markup\n\nUsage:\n stimeo check [--json|--github] <path...>\n Check HTML/ERB files (or directories) for\n unknown or misused stimeo--* controllers,\n targets, values and action methods.\n stimeo catalog [--json] Print the official controller catalog\n (identifiers, targets, values, actions,\n events).\n stimeo mcp Run a Model Context Protocol server over\n stdio, exposing the checker, catalog, and\n verified example markup as read-only tools\n (stimeo_check, stimeo_catalog,\n stimeo_controller, stimeo_example),\n resources, and workflow prompts for AI\n coding agents.\n\n--json makes either command emit machine-readable JSON (for tooling / MCP):\ncheck prints a CheckReport, catalog prints the raw manifest.\n--github prints check results as GitHub Actions workflow commands\n(::error / ::warning), which CI renders as inline PR annotations.\nExit code is 1 when any error is found (warnings never fail the run).`;\n\n/**\n * Runs the CLI.\n *\n * @param argv - Arguments after the node executable and script (`process.argv.slice(2)`).\n * @param write - Output sink (defaults to stdout); injectable for tests.\n * @param load - Manifest loader (defaults to the bundled manifest); injectable for tests.\n * @returns Process exit code (0 = clean, 1 = errors found, 2 = usage error).\n */\nexport function runCli(\n argv: readonly string[],\n write: (line: string) => void = console.log,\n load: () => Manifest = loadManifest,\n): number {\n const [command, ...rest] = argv;\n\n if (command === undefined || command === \"--help\" || command === \"-h\") {\n write(USAGE);\n return command === undefined ? 2 : 0;\n }\n\n const json = rest.includes(\"--json\");\n const github = rest.includes(\"--github\");\n if (json && github) {\n write(`--json and --github are mutually exclusive.\\n\\n${USAGE}`);\n return 2;\n }\n\n if (command === \"catalog\") {\n const manifest = load();\n if (json) {\n write(JSON.stringify(manifest, null, 2));\n } else {\n for (const line of catalogSummary(manifest)) write(line);\n }\n return 0;\n }\n\n if (command !== \"check\") {\n write(`Unknown command \"${command}\".\\n\\n${USAGE}`);\n return 2;\n }\n\n const paths = rest.filter((arg) => !arg.startsWith(\"-\"));\n if (paths.length === 0) {\n write(`No paths given.\\n\\n${USAGE}`);\n return 2;\n }\n\n const files: string[] = [];\n for (const path of paths) {\n try {\n collectFiles(path, files);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n const reason =\n code === \"ENOENT\"\n ? \"no such file or directory\"\n : code === \"EACCES\"\n ? \"permission denied\"\n : ((err as Error).message ?? \"cannot access path\");\n write(`Cannot read path \"${path}\": ${reason}.\\n\\n${USAGE}`);\n return 2;\n }\n }\n\n const manifest = load();\n const cwd = process.cwd();\n const reports: FileReport[] = [];\n for (const file of files.sort()) {\n reports.push({\n file: relative(cwd, file) || file,\n diagnostics: checkFile(file, manifest).diagnostics,\n });\n }\n const summary = buildCheckReport(reports, files.length);\n\n if (json) {\n write(JSON.stringify(summary, null, 2));\n return summary.errorCount > 0 ? 1 : 0;\n }\n\n if (github) {\n for (const report of summary.files) {\n for (const d of report.diagnostics) write(formatGithubAnnotation(report.file, d));\n }\n } else {\n for (const report of summary.files) {\n write(report.file);\n for (const d of report.diagnostics) write(formatDiagnostic(d));\n write(\"\");\n }\n }\n\n const total = summary.errorCount + summary.warningCount;\n if (total === 0) {\n write(`✓ Checked ${summary.checkedFiles} file(s); no problems found.`);\n return 0;\n }\n write(\n `✖ ${total} problem(s) (${summary.errorCount} error(s), ${summary.warningCount} warning(s)).`,\n );\n return summary.errorCount > 0 ? 1 : 0;\n}\n","/**\n * Prompt definitions for the `stimeo mcp` server (`prompts/list` /\n * `prompts/get`).\n *\n * Prompts are user-invokable workflow templates (surfaced as slash commands\n * in Claude Code, for example) that bake in the correct tool sequence —\n * discover via `stimeo_catalog`, pull the contract via `stimeo_controller`,\n * reference `stimeo_example`, and validate with `stimeo_check` before\n * presenting — so the calling model does not have to rediscover the workflow\n * each time. They are static text with argument interpolation; all live data\n * still flows through the tools.\n *\n * Handlers are pure (`(name, args) → messages`) like the tool handlers, so\n * they are unit-tested without a protocol round-trip.\n */\n\n/** One argument accepted by a prompt, as advertised in `prompts/list`. */\nexport interface PromptArgumentDescriptor {\n readonly name: string;\n readonly description: string;\n readonly required: boolean;\n}\n\n/** One entry of the `prompts/list` response. */\nexport interface PromptDescriptor {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly arguments: readonly PromptArgumentDescriptor[];\n}\n\n/** One message of a `prompts/get` result (this server emits text only). */\nexport interface PromptMessage {\n readonly role: \"user\";\n readonly content: { readonly type: \"text\"; readonly text: string };\n}\n\n/** The `prompts/get` result payload. */\nexport interface PromptResult {\n readonly description: string;\n readonly messages: readonly PromptMessage[];\n}\n\n/**\n * Raised when `prompts/get` names an unknown prompt or passes malformed\n * arguments. The server maps this to a JSON-RPC \"Invalid params\" (-32602)\n * protocol error, per the MCP prompts spec.\n */\nexport class InvalidPromptRequestError extends Error {}\n\n/**\n * Narrows unknown `prompts/get` arguments to a string-valued record (the MCP\n * prompts spec allows string values only), treating absence as empty and\n * rejecting keys the prompt does not declare.\n */\nfunction asPromptArgs(args: unknown, allowed: readonly string[]): Record<string, string> {\n if (args === undefined || args === null) return {};\n if (typeof args !== \"object\" || Array.isArray(args)) {\n throw new InvalidPromptRequestError(\"Prompt arguments must be an object.\");\n }\n const record = args as Record<string, unknown>;\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(record)) {\n if (!allowed.includes(key)) {\n throw new InvalidPromptRequestError(`Unknown argument \"${key}\".`);\n }\n if (typeof value !== \"string\") {\n throw new InvalidPromptRequestError(`Argument \"${key}\" must be a string.`);\n }\n result[key] = value;\n }\n return result;\n}\n\n/** Reads a required argument, present and non-empty. */\nfunction requireArg(record: Record<string, string>, key: string): string {\n const value = record[key];\n if (value === undefined || value.trim() === \"\") {\n throw new InvalidPromptRequestError(`Argument \"${key}\" is required.`);\n }\n return value;\n}\n\n/**\n * Reads an optional argument, trimmed; a blank value counts as absent so a\n * whitespace-only slash-command input cannot leak into the prompt text.\n */\nfunction optionalArg(record: Record<string, string>, key: string): string | undefined {\n const value = record[key]?.trim();\n return value ? value : undefined;\n}\n\n/** Builds the `stimeo_build_ui` messages. */\nfunction buildUiPrompt(args: Record<string, string>): PromptResult {\n const request = requireArg(args, \"request\");\n const controller = optionalArg(args, \"controller\");\n const start = controller\n ? `Start from the controller \"${controller}\" (verify it exists with stimeo_controller; ` +\n \"if it does not, fall back to discovery via stimeo_catalog).\"\n : \"Call stimeo_catalog to find the controller(s) that fit the task.\";\n const text =\n \"You are building UI for a Rails app with Stimeo UI, a headless (behavior-only) Stimulus \" +\n \"framework driven by data-* attributes. It ships no CSS; styling is the app's own.\\n\\n\" +\n `Task: ${request}\\n\\n` +\n \"Follow this workflow with the stimeo MCP tools:\\n\" +\n `1. ${start}\\n` +\n \"2. Call stimeo_controller for each chosen controller to get its contract: required \" +\n \"targets, author-supplied ARIA, keyboard prerequisites, and the ARIA it manages at \" +\n \"runtime (never hardcode those managed attributes).\\n\" +\n \"3. Call stimeo_example for each chosen controller and use the verified markup as your \" +\n \"structural reference.\\n\" +\n \"4. Write the markup: keep every data-*, role, and aria-* attribute the contract and \" +\n \"example require; replace demo class attributes with the app's own styling.\\n\" +\n \"5. Call stimeo_check on the markup you wrote and fix every diagnostic (each one carries \" +\n \"a fix suggestion when available). Repeat until ok is true — only then present the \" +\n \"result.\";\n return {\n description: \"Build Stimeo UI markup with the discover → contract → example → check workflow.\",\n messages: [{ role: \"user\", content: { type: \"text\", text } }],\n };\n}\n\n/** Builds the `stimeo_fix_markup` messages. */\nfunction fixMarkupPrompt(args: Record<string, string>): PromptResult {\n const source = requireArg(args, \"source\");\n const filename = optionalArg(args, \"filename\");\n const filenameClause = filename ? ` (filename: \"${filename}\")` : \"\";\n // The source is fenced so its own prose cannot read as workflow steps.\n const text =\n \"You are reviewing existing markup that uses Stimeo UI (stimeo--*) controllers.\\n\\n\" +\n `1. Call stimeo_check with the fenced source below${filenameClause}.\\n` +\n \"2. For each diagnostic, apply its fix suggestion; when a fix needs context, call \" +\n \"stimeo_controller for the affected controller's contract and stimeo_example for verified \" +\n \"reference markup.\\n\" +\n \"3. Re-run stimeo_check on the corrected markup until ok is true.\\n\" +\n \"4. Present the corrected markup and a short list of what changed and why.\\n\\n\" +\n `Source:\\n\\n\\`\\`\\`erb\\n${source}\\n\\`\\`\\``;\n return {\n description: \"Check the given markup and fix every diagnostic until stimeo_check passes.\",\n messages: [{ role: \"user\", content: { type: \"text\", text } }],\n };\n}\n\n/** One prompt: its `prompts/list` descriptor plus its message builder. */\ninterface PromptDefinition {\n readonly descriptor: PromptDescriptor;\n readonly build: (args: Record<string, string>) => PromptResult;\n}\n\n/**\n * The prompts this server serves. Descriptor and builder live side by side so\n * a prompt cannot be advertised without being dispatchable (adding an entry\n * here is the whole registration).\n */\nconst PROMPTS: readonly PromptDefinition[] = [\n {\n descriptor: {\n name: \"stimeo_build_ui\",\n title: \"Build UI with Stimeo UI\",\n description:\n \"Build Rails view markup for a requested UI using Stimeo UI controllers, following the \" +\n \"verified workflow: discover with stimeo_catalog, read the contract with \" +\n \"stimeo_controller, reference stimeo_example, and validate with stimeo_check before \" +\n \"presenting.\",\n arguments: [\n {\n name: \"request\",\n description: 'What to build, e.g. \"a confirmation dialog for deleting a project\".',\n required: true,\n },\n {\n name: \"controller\",\n description:\n 'Optional controller identifier to start from, e.g. \"stimeo--dialog\". ' +\n \"Omit to let the workflow discover one via stimeo_catalog.\",\n required: false,\n },\n ],\n },\n build: buildUiPrompt,\n },\n {\n descriptor: {\n name: \"stimeo_fix_markup\",\n title: \"Check and fix Stimeo UI markup\",\n description:\n \"Check existing HTML/ERB that uses stimeo--* controllers with stimeo_check, fix every \" +\n \"diagnostic using the fix suggestions and the controller contracts, and re-check until \" +\n \"clean.\",\n arguments: [\n {\n name: \"source\",\n description: \"The HTML or ERB source to check and fix.\",\n required: true,\n },\n {\n name: \"filename\",\n description: 'Optional filename for diagnostics, e.g. \"app/views/users/show.html.erb\".',\n required: false,\n },\n ],\n },\n build: fixMarkupPrompt,\n },\n];\n\n/** Prompt descriptors advertised via `prompts/list`. */\nexport const PROMPT_DESCRIPTORS: readonly PromptDescriptor[] = PROMPTS.map(\n (prompt) => prompt.descriptor,\n);\n\n/**\n * Dispatches one `prompts/get` invocation to its builder.\n *\n * @throws InvalidPromptRequestError for unknown prompt names or malformed\n * arguments (mapped to JSON-RPC -32602 by the server).\n */\nexport function getPrompt(name: string, args: unknown): PromptResult {\n const prompt = PROMPTS.find((entry) => entry.descriptor.name === name);\n if (!prompt) {\n throw new InvalidPromptRequestError(`Unknown prompt \"${name}\".`);\n }\n const record = asPromptArgs(\n args,\n prompt.descriptor.arguments.map((argument) => argument.name),\n );\n return prompt.build(record);\n}\n","import { checkSource, didYouMean } from \"../check\";\nimport { buildCheckReport, sortedControllerEntries } from \"../cli\";\nimport type { ExamplesIndex } from \"../examples\";\nimport type { CheckReport, ControllerManifest, Manifest } from \"../types\";\nimport { DIAGNOSTIC_CODES } from \"../types\";\n\n/**\n * Tool definitions and pure handlers for the `stimeo mcp` server.\n *\n * Each MCP tool wraps an existing pure engine function ({@link checkSource},\n * {@link buildCheckReport}, manifest lookups) so the server, the CLI, and the\n * project's own CI gate share exactly the same code path. Each handler takes\n * `args` plus the slice of {@link ToolContext} it needs (the manifest, the\n * example index, or both) and returns a plain JSON-serializable object; the\n * handlers perform no I/O, so they are unit-tested directly without a\n * protocol round-trip.\n *\n * All tools are read-only: `stimeo_check` inspects a source string passed by\n * the client (no filesystem traversal), the others only read the bundled\n * manifest and example index.\n */\n\n/** Names of the tools exposed by the MCP server. */\nexport type ToolName = \"stimeo_check\" | \"stimeo_catalog\" | \"stimeo_controller\" | \"stimeo_example\";\n\n/**\n * Everything the tool dispatcher needs: the reflected manifest plus the\n * bundled example index (both generated at build time next to the CLI).\n */\nexport interface ToolContext {\n readonly manifest: Manifest;\n readonly examples: ExamplesIndex;\n}\n\n/** Minimal JSON Schema subset used to describe tool inputs in `tools/list`. */\nexport interface ToolInputSchema {\n readonly type: \"object\";\n readonly properties: Readonly<\n Record<string, { readonly type: string; readonly description: string }>\n >;\n readonly required?: readonly string[];\n readonly additionalProperties: boolean;\n}\n\n/**\n * MCP tool annotations (protocol 2025-03-26+): machine-readable behavior hints.\n * Every v1 tool is read-only and closed-world (it only consults the bundled\n * manifest and the strings the client sends), so clients can skip destructive-\n * action confirmation UX.\n */\nexport interface ToolAnnotations {\n readonly readOnlyHint: boolean;\n readonly openWorldHint: boolean;\n}\n\n/**\n * JSON Schema for a tool result (`outputSchema` in `tools/list`). Typed as a\n * plain JSON object rather than a full JSON Schema model: the schemas below\n * are hand-written literals, and their conformance to what the handlers\n * actually return is locked by `mcp_tools.test.ts`.\n */\nexport type ToolOutputSchema = Readonly<Record<string, unknown>>;\n\n/** One entry of the `tools/list` response. */\nexport interface ToolDescriptor {\n readonly name: ToolName;\n readonly title: string;\n readonly description: string;\n readonly annotations: ToolAnnotations;\n readonly inputSchema: ToolInputSchema;\n readonly outputSchema: ToolOutputSchema;\n}\n\n/** Shared annotations: every v1 tool is read-only over bundled data. */\nconst READ_ONLY_ANNOTATIONS: ToolAnnotations = { readOnlyHint: true, openWorldHint: false };\n\n/** JSON Schema fragment for a `readonly string[]` field. */\nconst STRING_ARRAY = { type: \"array\", items: { type: \"string\" } } as const;\n\n/** JSON Schema for one diagnostic inside a {@link CheckReport}. */\nconst DIAGNOSTIC_SCHEMA = {\n type: \"object\",\n properties: {\n code: { type: \"string\", enum: DIAGNOSTIC_CODES },\n severity: { type: \"string\", enum: [\"error\", \"warning\"] },\n message: { type: \"string\" },\n line: { type: \"integer\", description: \"1-based line where the problem was detected.\" },\n column: { type: \"integer\", description: \"1-based column where the problem was detected.\" },\n suggestion: { type: \"string\", description: \"Fix suggestion (stage 4), when available.\" },\n },\n required: [\"code\", \"severity\", \"message\", \"line\", \"column\"],\n} as const;\n\n/** JSON Schema for the `stimeo_check` result (mirrors {@link CheckReport}). */\nconst CHECK_REPORT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n description: \"Aggregated check result; same shape as `stimeo check --json`.\",\n properties: {\n ok: { type: \"boolean\", description: \"True when no error-severity diagnostics were found.\" },\n checkedFiles: { type: \"integer\" },\n errorCount: { type: \"integer\" },\n warningCount: { type: \"integer\" },\n files: {\n type: \"array\",\n description: \"Only files that produced at least one diagnostic.\",\n items: {\n type: \"object\",\n properties: {\n file: { type: \"string\" },\n diagnostics: { type: \"array\", items: DIAGNOSTIC_SCHEMA },\n },\n required: [\"file\", \"diagnostics\"],\n },\n },\n },\n required: [\"ok\", \"checkedFiles\", \"errorCount\", \"warningCount\", \"files\"],\n};\n\n/** JSON Schema for the `stimeo_catalog` result (mirrors {@link CatalogResult}). */\nconst CATALOG_RESULT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n properties: {\n schemaVersion: { type: \"integer\" },\n packageVersion: { type: \"string\" },\n controllerCount: { type: \"integer\" },\n controllers: {\n type: \"object\",\n description: 'Keyed by controller identifier, e.g. \"stimeo--menu\".',\n additionalProperties: {\n type: \"object\",\n properties: {\n targets: STRING_ARRAY,\n values: STRING_ARRAY,\n actions: STRING_ARRAY,\n events: STRING_ARRAY,\n },\n required: [\"targets\", \"values\", \"actions\", \"events\"],\n },\n },\n },\n required: [\"schemaVersion\", \"packageVersion\", \"controllerCount\", \"controllers\"],\n};\n\n/** JSON Schema for the `stimeo_example` result (mirrors {@link ExampleResult}). */\nconst EXAMPLE_RESULT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: 'Controller identifier, e.g. \"stimeo--menu\".' },\n file: {\n type: \"string\",\n description: \"Repo-relative provenance of the example (the catalog demo sidecar).\",\n },\n source: { type: \"string\", description: \"The HTML/ERB example source.\" },\n guidance: { type: \"string\", description: \"How to consume the example correctly.\" },\n },\n required: [\"id\", \"file\", \"source\", \"guidance\"],\n};\n\n/** JSON Schema for the `stimeo_controller` result (mirrors {@link ControllerContract}). */\nconst CONTROLLER_CONTRACT_SCHEMA: ToolOutputSchema = {\n type: \"object\",\n properties: {\n id: { type: \"string\", description: 'Controller identifier, e.g. \"stimeo--tabs\".' },\n targets: STRING_ARRAY,\n values: STRING_ARRAY,\n actions: STRING_ARRAY,\n events: STRING_ARRAY,\n requiredTargets: {\n ...STRING_ARRAY,\n description: \"Targets that must be present at least once inside the controller scope.\",\n },\n a11y: {\n type: \"array\",\n description: \"Author-supplied ARIA the controller relies on but never sets itself.\",\n items: {\n type: \"object\",\n properties: {\n target: {\n type: \"string\",\n description: 'Target name; \"\" means the data-controller element itself.',\n },\n attrs: { ...STRING_ARRAY, description: \"At least one of these must be present.\" },\n values: { ...STRING_ARRAY, description: \"Allowed values; absent = any value.\" },\n or: {\n type: \"array\",\n description: \"Alternative attribute groups; satisfying any group satisfies the rule.\",\n items: {\n type: \"object\",\n properties: { attrs: STRING_ARRAY, values: STRING_ARRAY },\n required: [\"attrs\"],\n },\n },\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"attrs\", \"suggestion\"],\n },\n },\n keyboard: {\n type: \"array\",\n description: \"Targets whose keyboard focusability the author must provide.\",\n items: {\n type: \"object\",\n properties: {\n target: { type: \"string\" },\n reach: {\n type: \"string\",\n enum: [\"tab\", \"focus\"],\n description: 'How focus arrives; defaults to \"tab\" (steady Tab stop).',\n },\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"suggestion\"],\n },\n },\n managedAria: {\n type: \"array\",\n description: \"ARIA the controller recomputes at runtime; authoring it is a warning.\",\n items: {\n type: \"object\",\n properties: {\n target: { type: \"string\" },\n attrs: STRING_ARRAY,\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"attrs\", \"suggestion\"],\n },\n },\n compositions: {\n type: \"array\",\n description:\n \"Cross-controller value alignments: when the companion controller is co-located on \" +\n \"the named target, its value (authored or default) must be one of the allowed set.\",\n items: {\n type: \"object\",\n properties: {\n target: {\n type: \"string\",\n description: 'Host target hosting the companion; \"\" means the data-controller element.',\n },\n fallbackToScope: {\n type: \"boolean\",\n description: \"Check the scope element when the target is absent.\",\n },\n coController: { type: \"string\", description: \"Companion controller identifier.\" },\n when: {\n type: \"object\",\n description: \"Host-value condition arming the rule; absent means unconditional.\",\n properties: {\n value: { type: \"string\" },\n equals: STRING_ARRAY,\n default: { type: \"string\" },\n },\n required: [\"value\", \"equals\", \"default\"],\n },\n require: {\n type: \"object\",\n description: \"Companion-value requirement (first allowed value is canonical).\",\n properties: {\n value: { type: \"string\" },\n oneOf: STRING_ARRAY,\n default: { type: \"string\" },\n },\n required: [\"value\", \"oneOf\", \"default\"],\n },\n suggestion: { type: \"string\" },\n },\n required: [\"target\", \"coController\", \"require\", \"suggestion\"],\n },\n },\n },\n required: [\n \"id\",\n \"targets\",\n \"values\",\n \"actions\",\n \"events\",\n \"requiredTargets\",\n \"a11y\",\n \"keyboard\",\n \"managedAria\",\n \"compositions\",\n ],\n};\n\n/**\n * Raised when `tools/call` arguments fail validation. The server maps this to\n * a JSON-RPC \"Invalid params\" (-32602) protocol error, per the MCP spec's\n * distinction between protocol errors and tool execution errors.\n */\nexport class InvalidToolArgsError extends Error {}\n\n/**\n * Raised when a tool runs but cannot produce a result (e.g. unknown controller\n * id). The server maps this to a tool result with `isError: true`, so the\n * calling model sees the message and can self-correct.\n */\nexport class ToolExecutionError extends Error {}\n\n/** Report filename used by `stimeo_check` when the client does not send one. */\nexport const DEFAULT_CHECK_FILENAME = \"source.erb\";\n\n/** Catalog view of one controller: the reflected `data-*` API surface only. */\nexport interface CatalogController {\n readonly targets: readonly string[];\n readonly values: readonly string[];\n readonly actions: readonly string[];\n readonly events: readonly string[];\n}\n\n/**\n * Result of `stimeo_catalog`: every controller's API surface, without the\n * per-controller contract rules (those come from `stimeo_controller`), keeping\n * the discovery payload small for model consumption.\n */\nexport interface CatalogResult {\n readonly schemaVersion: number;\n readonly packageVersion: string;\n readonly controllerCount: number;\n readonly controllers: Readonly<Record<string, CatalogController>>;\n}\n\n/** Result of `stimeo_controller`: the full manifest entry plus its id. */\nexport interface ControllerContract extends ControllerManifest {\n readonly id: string;\n}\n\n/** Result of `stimeo_example`: one controller's verified example markup. */\nexport interface ExampleResult {\n readonly id: string;\n /** Repo-relative provenance of the example (the catalog demo sidecar). */\n readonly file: string;\n /** The HTML/ERB source. */\n readonly source: string;\n /** How to consume the example correctly ({@link EXAMPLE_GUIDANCE}). */\n readonly guidance: string;\n}\n\n/**\n * Consumption note attached to every `stimeo_example` result. The examples are\n * headless-catalog demos: the `stimeo--*` data attributes are the contract;\n * class attributes are demo styling placeholders the consumer must replace.\n */\nexport const EXAMPLE_GUIDANCE =\n \"Verified example from the official Stimeo UI catalog (it passes stimeo_check against the \" +\n \"bundled manifest). Behavior and accessibility come from the data-* attributes and any \" +\n \"role/aria-* attributes shown; keep those intact. class attributes are demo styling \" +\n \"placeholders — the library ships no CSS, so replace them with your own classes. ERB \" +\n \"helpers/comments illustrate Rails usage and can be adapted.\";\n\n/** Tool descriptors advertised via `tools/list`. */\nexport const TOOL_DESCRIPTORS: readonly ToolDescriptor[] = [\n {\n name: \"stimeo_check\",\n title: \"Check Stimeo UI markup\",\n description:\n \"Statically check HTML or ERB source that uses Stimeo UI (stimeo--*) controllers. \" +\n \"Returns a CheckReport with diagnostics — unknown controllers/targets/values/action \" +\n \"methods, missing required targets, missing or invalid author-supplied ARIA, \" +\n \"keyboard-focusability prerequisites, and misaligned cross-controller composition \" +\n \"values — each with a fix suggestion when available. \" +\n \"Call this on generated markup before finalizing it; ok=true means no errors.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {\n source: {\n type: \"string\",\n description: \"The HTML or ERB source to check.\",\n },\n filename: {\n type: \"string\",\n description:\n 'Optional filename reported in diagnostics (e.g. \"app/views/users/show.html.erb\").',\n },\n },\n required: [\"source\"],\n additionalProperties: false,\n },\n outputSchema: CHECK_REPORT_SCHEMA,\n },\n {\n name: \"stimeo_catalog\",\n title: \"List Stimeo UI controllers\",\n description:\n \"List every Stimeo UI controller with its targets, values, actions, and events. \" +\n \"Use this to discover which stimeo--* controllers exist and the data-* API each \" +\n \"accepts before writing markup.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n outputSchema: CATALOG_RESULT_SCHEMA,\n },\n {\n name: \"stimeo_controller\",\n title: \"Get one controller's usage contract\",\n description:\n \"Fetch the full usage contract of one Stimeo UI controller by identifier \" +\n '(e.g. \"stimeo--tabs\"): targets, values, actions, events, required targets, and the ' +\n \"accessibility contract — author-supplied ARIA requirements, keyboard-focusability \" +\n \"prerequisites, the ARIA attributes the controller manages at runtime (which the \" +\n \"author must NOT hardcode), and cross-controller composition value alignments.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: 'Controller identifier, e.g. \"stimeo--tabs\".',\n },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n outputSchema: CONTROLLER_CONTRACT_SCHEMA,\n },\n {\n name: \"stimeo_example\",\n title: \"Get one controller's verified example markup\",\n description:\n \"Fetch verified example markup for one Stimeo UI controller by identifier \" +\n '(e.g. \"stimeo--menu\"). The example is the official catalog demo — it passes ' +\n \"stimeo_check against the bundled manifest, so use it as the reference for correct \" +\n \"structure, required targets, and author-supplied ARIA. class attributes in it are \" +\n \"demo styling placeholders to replace; the stimeo--* data attributes and role/aria-* \" +\n \"attributes are the contract to keep.\",\n annotations: READ_ONLY_ANNOTATIONS,\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: 'Controller identifier, e.g. \"stimeo--menu\".',\n },\n },\n required: [\"id\"],\n additionalProperties: false,\n },\n outputSchema: EXAMPLE_RESULT_SCHEMA,\n },\n];\n\n/**\n * Narrows unknown `tools/call` arguments to a record, treating absence as\n * empty. Unknown keys are rejected so behavior matches the advertised\n * `additionalProperties: false` in every tool's input schema.\n */\nfunction asArgsRecord(args: unknown, allowed: readonly string[]): Record<string, unknown> {\n if (args === undefined || args === null) return {};\n if (typeof args !== \"object\" || Array.isArray(args)) {\n throw new InvalidToolArgsError(\"Tool arguments must be an object.\");\n }\n const record = args as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!allowed.includes(key)) {\n throw new InvalidToolArgsError(`Unknown argument \"${key}\".`);\n }\n }\n return record;\n}\n\n/** Reads a required string property from tool arguments. */\nfunction requireString(record: Record<string, unknown>, key: string): string {\n const value = record[key];\n if (typeof value !== \"string\") {\n throw new InvalidToolArgsError(`Argument \"${key}\" is required and must be a string.`);\n }\n return value;\n}\n\n/** Reads an optional string property from tool arguments. */\nfunction optionalString(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n if (value === undefined) return undefined;\n if (typeof value !== \"string\") {\n throw new InvalidToolArgsError(`Argument \"${key}\" must be a string when given.`);\n }\n return value;\n}\n\n/**\n * `stimeo_check`: runs the engine on one in-memory source and aggregates the\n * diagnostics into a {@link CheckReport}, exactly like `stimeo check --json`\n * does for files on disk.\n */\nexport function runCheckTool(manifest: Manifest, args: unknown): CheckReport {\n const record = asArgsRecord(args, [\"source\", \"filename\"]);\n const source = requireString(record, \"source\");\n const filename = optionalString(record, \"filename\") ?? DEFAULT_CHECK_FILENAME;\n return buildCheckReport([{ file: filename, diagnostics: checkSource(source, manifest) }], 1);\n}\n\n/** `stimeo_catalog`: the API surface of every controller, sorted by identifier. */\nexport function runCatalogTool(manifest: Manifest): CatalogResult {\n // Null-prototype dictionary: manifest keys come from parsed JSON, and\n // assigning a hostile \"__proto__\" key onto a plain object would silently\n // rewrite the dictionary's prototype instead of storing the entry.\n const controllers: Record<string, CatalogController> = Object.create(null);\n for (const [id, controller] of sortedControllerEntries(manifest)) {\n controllers[id] = {\n targets: controller.targets,\n values: controller.values,\n actions: controller.actions,\n events: controller.events,\n };\n }\n return {\n schemaVersion: manifest.schemaVersion,\n packageVersion: manifest.packageVersion,\n controllerCount: Object.keys(controllers).length,\n controllers,\n };\n}\n\n/**\n * Prototype-safe dictionary lookup. The manifest and example dictionaries are\n * parsed JSON, so bare bracket access would resolve prototype keys\n * (\"constructor\", \"toString\", \"__proto__\", …) to inherited members and fake a\n * successful lookup for a nonexistent id — a hostile key must read as absent.\n */\nexport function getOwn<T>(dict: Readonly<Record<string, T>>, key: string): T | undefined {\n return Object.hasOwn(dict, key) ? dict[key] : undefined;\n}\n\n/**\n * `stimeo_controller`: one controller's full contract (a11y and keyboard\n * requirements included). Unknown ids produce a tool execution error with a\n * \"did you mean\" hint so the calling model can self-correct.\n */\nexport function runControllerTool(manifest: Manifest, args: unknown): ControllerContract {\n const record = asArgsRecord(args, [\"id\"]);\n const id = requireString(record, \"id\");\n const controller = getOwn(manifest.controllers, id);\n if (!controller) {\n const hint = didYouMean(id, Object.keys(manifest.controllers));\n throw new ToolExecutionError(\n `Unknown controller \"${id}\".${hint ? ` ${hint}` : \"\"} Use stimeo_catalog to list available controllers.`,\n );\n }\n return { id, ...controller };\n}\n\n/**\n * `stimeo_example`: one controller's verified example markup, straight from\n * the bundled catalog-demo index. Unknown ids produce a tool execution error\n * with a \"did you mean\" hint so the calling model can self-correct.\n */\nexport function runExampleTool(examples: ExamplesIndex, args: unknown): ExampleResult {\n const record = asArgsRecord(args, [\"id\"]);\n const id = requireString(record, \"id\");\n const entry = getOwn(examples.examples, id);\n if (!entry) {\n const hint = didYouMean(id, Object.keys(examples.examples));\n throw new ToolExecutionError(\n `No example for controller \"${id}\".${hint ? ` ${hint}` : \"\"} Use stimeo_catalog to list available controllers.`,\n );\n }\n return { id, file: entry.file, source: entry.source, guidance: EXAMPLE_GUIDANCE };\n}\n\n/**\n * Dispatches one `tools/call` invocation to its handler.\n *\n * @throws InvalidToolArgsError for unknown tool names or malformed arguments\n * (protocol error), {@link ToolExecutionError} for failures inside a tool\n * (returned as an `isError` tool result).\n */\nexport function callTool(context: ToolContext, name: string, args: unknown): unknown {\n switch (name) {\n case \"stimeo_check\":\n return runCheckTool(context.manifest, args);\n case \"stimeo_catalog\":\n asArgsRecord(args, []);\n return runCatalogTool(context.manifest);\n case \"stimeo_controller\":\n return runControllerTool(context.manifest, args);\n case \"stimeo_example\":\n return runExampleTool(context.examples, args);\n default:\n throw new InvalidToolArgsError(`Unknown tool \"${name}\".`);\n }\n}\n","import { createInterface } from \"node:readline\";\nimport type { Readable } from \"node:stream\";\nimport { getPrompt, InvalidPromptRequestError, PROMPT_DESCRIPTORS } from \"./prompts\";\nimport type { ToolContext } from \"./tools\";\nimport {\n callTool,\n getOwn,\n InvalidToolArgsError,\n TOOL_DESCRIPTORS,\n ToolExecutionError,\n} from \"./tools\";\n\n/**\n * `stimeo mcp` — a zero-dependency Model Context Protocol server over stdio.\n *\n * Implements the JSON-RPC 2.0 subset an MCP client needs to use the Inspector\n * as read-only tools, resources, and prompts: `initialize`, the\n * `notifications/initialized` notification, `ping`, `tools/list`,\n * `tools/call`, `resources/list`, `resources/read`, `prompts/list`, and\n * `prompts/get` (newline-delimited messages, one per line). It is hand-written\n * to keep the shipped server dependency-free; this bounded subset is small\n * enough to implement and review directly.\n *\n * stdout carries protocol messages only; anything diagnostic must go to the\n * caller-provided error log (stderr in production).\n */\n\n/** Latest MCP protocol revision this server implements. */\nexport const LATEST_PROTOCOL_VERSION = \"2025-06-18\";\n\n/**\n * Revisions this server can speak. The tools-only subset is identical across\n * these revisions, so we echo whichever supported version the client asks for\n * and otherwise answer with the latest (per the MCP version-negotiation rule).\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS: readonly string[] = [\n LATEST_PROTOCOL_VERSION,\n \"2025-03-26\",\n \"2024-11-05\",\n];\n\n/** JSON-RPC 2.0 error codes used by this server. */\nexport const JSONRPC_PARSE_ERROR = -32700;\nexport const JSONRPC_INVALID_REQUEST = -32600;\nexport const JSONRPC_METHOD_NOT_FOUND = -32601;\nexport const JSONRPC_INVALID_PARAMS = -32602;\nexport const JSONRPC_INTERNAL_ERROR = -32603;\n/**\n * MCP server-defined code (-32002). The spec assigns it both to requests sent\n * before `initialize` and to `resources/read` of an unknown URI; the two named\n * constants keep call sites self-documenting.\n */\nexport const JSONRPC_SERVER_NOT_INITIALIZED = -32002;\n/** See {@link JSONRPC_SERVER_NOT_INITIALIZED} — same spec-assigned code. */\nexport const JSONRPC_RESOURCE_NOT_FOUND = -32002;\n\n/** URI of the full-manifest resource. */\nexport const MANIFEST_RESOURCE_URI = \"stimeo://manifest\";\n/** URI prefix of the per-controller example resources. */\nexport const EXAMPLE_RESOURCE_PREFIX = \"stimeo://examples/\";\n\n/**\n * Request id this server accepts. MCP tightens bare JSON-RPC 2.0 here: a\n * request id MUST NOT be null, so `id: null` requests are rejected as invalid\n * rather than answered.\n */\ntype JsonRpcId = string | number;\n\n/**\n * Id an error response may carry: null only for messages whose id could not\n * be established (unparsable lines, malformed requests), per JSON-RPC 2.0.\n */\ntype JsonRpcErrorId = JsonRpcId | null;\n\ninterface JsonRpcSuccess {\n readonly jsonrpc: \"2.0\";\n readonly id: JsonRpcId;\n readonly result: unknown;\n}\n\ninterface JsonRpcError {\n readonly jsonrpc: \"2.0\";\n readonly id: JsonRpcErrorId;\n readonly error: { readonly code: number; readonly message: string };\n}\n\n/** Builds a serialized JSON-RPC success response. */\nfunction success(id: JsonRpcId, result: unknown): string {\n const response: JsonRpcSuccess = { jsonrpc: \"2.0\", id, result };\n return JSON.stringify(response);\n}\n\n/** Builds a serialized JSON-RPC error response. */\nfunction failure(id: JsonRpcErrorId, code: number, message: string): string {\n const response: JsonRpcError = { jsonrpc: \"2.0\", id, error: { code, message } };\n return JSON.stringify(response);\n}\n\n/** Narrows an unknown parsed message to a record. */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n}\n\n/**\n * One MCP session: a tiny state machine over parsed JSON-RPC messages.\n * Transport-free so tests can drive it line by line; {@link runMcpServer}\n * wires it to a readable stream.\n */\nexport class McpSession {\n #context: ToolContext;\n #initialized = false;\n\n constructor(context: ToolContext) {\n this.#context = context;\n }\n\n /**\n * Handles one newline-delimited message.\n *\n * @returns The serialized response line, or null when no response is due\n * (blank lines and notifications).\n */\n handleLine(line: string): string | null {\n const trimmed = line.trim();\n if (trimmed === \"\") return null;\n let message: unknown;\n try {\n message = JSON.parse(trimmed);\n } catch {\n return failure(null, JSONRPC_PARSE_ERROR, \"Parse error\");\n }\n return this.#handleMessage(message);\n }\n\n #handleMessage(message: unknown): string | null {\n const record = asRecord(message);\n // JSON-RPC batches were removed in MCP 2025-06-18; reject them explicitly.\n if (record === null || record.jsonrpc !== \"2.0\" || typeof record.method !== \"string\") {\n return failure(null, JSONRPC_INVALID_REQUEST, \"Invalid request\");\n }\n const method = record.method;\n const hasId = \"id\" in record;\n const id = record.id;\n if (!hasId) {\n // Notifications (initialized, cancelled, …) never get a response.\n return null;\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n // Covers `id: null` too: the MCP base protocol forbids null request\n // ids (unlike bare JSON-RPC 2.0), so it is rejected, not echoed.\n return failure(null, JSONRPC_INVALID_REQUEST, \"Invalid request id\");\n }\n return this.#handleRequest(id, method, record.params);\n }\n\n #handleRequest(id: JsonRpcId, method: string, params: unknown): string {\n if (method === \"initialize\") return this.#initialize(id, params);\n if (method === \"ping\") return success(id, {});\n if (!this.#initialized) {\n return failure(\n id,\n JSONRPC_SERVER_NOT_INITIALIZED,\n \"Server not initialized. Send an initialize request first.\",\n );\n }\n if (method === \"tools/list\") return success(id, { tools: TOOL_DESCRIPTORS });\n if (method === \"tools/call\") return this.#callTool(id, params);\n if (method === \"resources/list\") return success(id, { resources: this.#listResources() });\n if (method === \"resources/read\") return this.#readResource(id, params);\n if (method === \"prompts/list\") return success(id, { prompts: PROMPT_DESCRIPTORS });\n if (method === \"prompts/get\") return this.#getPrompt(id, params);\n return failure(id, JSONRPC_METHOD_NOT_FOUND, `Method not found: \"${method}\"`);\n }\n\n #initialize(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params) ?? {};\n const requested = typeof record.protocolVersion === \"string\" ? record.protocolVersion : \"\";\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested)\n ? requested\n : LATEST_PROTOCOL_VERSION;\n this.#initialized = true;\n return success(id, {\n protocolVersion,\n capabilities: {\n tools: { listChanged: false },\n resources: { subscribe: false, listChanged: false },\n prompts: { listChanged: false },\n },\n serverInfo: {\n name: \"stimeo-ui\",\n title: \"Stimeo UI Inspector\",\n version: this.#context.manifest.packageVersion,\n },\n instructions:\n \"Stimeo UI is a headless Stimulus UI framework for Rails. Use stimeo_catalog to \" +\n \"discover controllers, stimeo_controller for one controller's usage and \" +\n \"accessibility contract, stimeo_example for verified reference markup, and \" +\n \"stimeo_check to validate generated HTML/ERB before presenting it. The full \" +\n \"manifest and every example are also exposed as resources (stimeo:// URIs), and \" +\n \"the stimeo_build_ui / stimeo_fix_markup prompts bake this workflow into \" +\n \"user-invokable templates.\",\n });\n }\n\n #getPrompt(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params);\n const name = record?.name;\n if (typeof name !== \"string\") {\n return failure(id, JSONRPC_INVALID_PARAMS, 'prompts/get requires a string \"name\" param.');\n }\n try {\n return success(id, getPrompt(name, record?.arguments));\n } catch (error) {\n if (error instanceof InvalidPromptRequestError) {\n // Unknown prompt names and bad arguments are protocol errors per the\n // MCP prompts spec (unlike tool execution failures).\n return failure(id, JSONRPC_INVALID_PARAMS, error.message);\n }\n const message = error instanceof Error ? error.message : String(error);\n return failure(id, JSONRPC_INTERNAL_ERROR, `Internal error: ${message}`);\n }\n }\n\n /** Static resource listing: the manifest plus one example per controller. */\n #listResources(): readonly Record<string, unknown>[] {\n const resources: Record<string, unknown>[] = [\n {\n uri: MANIFEST_RESOURCE_URI,\n name: \"manifest\",\n title: \"Stimeo UI controller manifest\",\n description:\n \"The full reflected manifest: every controller's targets, values, actions, \" +\n \"events, required targets, and accessibility contract.\",\n mimeType: \"application/json\",\n },\n ];\n for (const id of Object.keys(this.#context.examples.examples).sort()) {\n resources.push({\n uri: `${EXAMPLE_RESOURCE_PREFIX}${id}`,\n name: id,\n title: `Example markup — ${id}`,\n description: `Verified catalog demo markup for ${id} (passes stimeo_check).`,\n mimeType: \"text/x-erb\",\n });\n }\n return resources;\n }\n\n #readResource(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params);\n const uri = record?.uri;\n if (typeof uri !== \"string\") {\n return failure(id, JSONRPC_INVALID_PARAMS, 'resources/read requires a string \"uri\" param.');\n }\n if (uri === MANIFEST_RESOURCE_URI) {\n return success(id, {\n contents: [\n {\n uri,\n mimeType: \"application/json\",\n text: JSON.stringify(this.#context.manifest, null, 2),\n },\n ],\n });\n }\n if (uri.startsWith(EXAMPLE_RESOURCE_PREFIX)) {\n const exampleId = uri.slice(EXAMPLE_RESOURCE_PREFIX.length);\n const entry = getOwn(this.#context.examples.examples, exampleId);\n if (entry) {\n return success(id, {\n contents: [{ uri, mimeType: \"text/x-erb\", text: entry.source }],\n });\n }\n }\n return failure(id, JSONRPC_RESOURCE_NOT_FOUND, `Resource not found: \"${uri}\"`);\n }\n\n #callTool(id: JsonRpcId, params: unknown): string {\n const record = asRecord(params);\n const name = record?.name;\n if (typeof name !== \"string\") {\n return failure(id, JSONRPC_INVALID_PARAMS, 'tools/call requires a string \"name\" param.');\n }\n try {\n const result = callTool(this.#context, name, record?.arguments);\n return success(id, {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n structuredContent: result,\n });\n } catch (error) {\n if (error instanceof InvalidToolArgsError) {\n return failure(id, JSONRPC_INVALID_PARAMS, error.message);\n }\n if (error instanceof ToolExecutionError) {\n // Tool execution errors flow back as results so the model can read\n // the message and self-correct (MCP tools spec).\n return success(id, {\n content: [{ type: \"text\", text: error.message }],\n isError: true,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return failure(id, JSONRPC_INTERNAL_ERROR, `Internal error: ${message}`);\n }\n }\n}\n\n/** I/O seams for {@link runMcpServer}; injectable for tests. */\nexport interface McpServerIo {\n /** Stream carrying newline-delimited JSON-RPC messages (stdin in production). */\n readonly input: Readable;\n /** Sink for one serialized response line (stdout in production). */\n readonly write: (line: string) => void;\n /**\n * Tool-context loader (the bundled `dist/inspector/manifest.json` and\n * `examples.json` in production).\n */\n readonly load: () => ToolContext;\n /** Diagnostic sink; must never be stdout (protocol-only). */\n readonly logError?: (message: string) => void;\n}\n\n/**\n * Runs the stdio server loop: one JSON-RPC message per input line, one\n * response per output line. Resolves when the input stream closes (the MCP\n * client disconnecting), which is the server's shutdown signal. Declared\n * async so a failing manifest load rejects the returned promise instead of\n * throwing synchronously past the caller's rejection handler.\n */\nexport async function runMcpServer(io: McpServerIo): Promise<void> {\n const session = new McpSession(io.load());\n const lines = createInterface({ input: io.input, crlfDelay: Number.POSITIVE_INFINITY });\n return new Promise((resolve) => {\n lines.on(\"line\", (line) => {\n try {\n const response = session.handleLine(line);\n if (response !== null) io.write(response);\n } catch (error) {\n // The session already converts per-request failures into JSON-RPC\n // errors; this guards the loop itself so one bad line cannot kill\n // the server.\n io.logError?.(error instanceof Error ? error.message : String(error));\n }\n });\n lines.on(\"close\", resolve);\n });\n}\n","import process from \"node:process\";\nimport { loadExamplesIndex, loadManifest, runCli } from \"./cli\";\nimport { runMcpServer } from \"./mcp/server\";\n\n/**\n * Executable entry point for the `stimeo` bin. Kept separate from {@link runCli}\n * so the CLI logic can be imported by tests without triggering `process.exit`.\n * A Node shebang is prepended to the built file by `scripts/postbuild.ts`.\n *\n * `stimeo mcp` is dispatched here rather than inside {@link runCli} because it\n * is not a run-to-completion command: it starts a resident stdio server that\n * only exits when the client closes stdin. Everything else keeps the original\n * synchronous exit-code contract.\n */\nconst argv = process.argv.slice(2);\n\nif (argv[0] === \"mcp\") {\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n process.exit(runCli([\"--help\"]));\n }\n // A disappearing client closes our stdout pipe; exit quietly on EPIPE\n // instead of crashing with an unhandled stream error.\n process.stdout.on(\"error\", (error: NodeJS.ErrnoException) => {\n process.exit(error.code === \"EPIPE\" ? 0 : 1);\n });\n runMcpServer({\n input: process.stdin,\n write: (line) => {\n process.stdout.write(`${line}\\n`);\n },\n load: () => ({ manifest: loadManifest(), examples: loadExamplesIndex() }),\n logError: (message) => {\n process.stderr.write(`stimeo mcp: ${message}\\n`);\n },\n }).then(\n // Set the exit code instead of calling process.exit so any buffered\n // stdout responses are flushed before the process ends.\n () => {\n process.exitCode = 0;\n },\n (error: unknown) => {\n process.stderr.write(\n `stimeo mcp: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n process.exitCode = 1;\n },\n );\n} else {\n process.exit(runCli(argv));\n}\n"]}
|