@vielzeug/codex 26.11.24 → 26.11.25

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.
Files changed (97) hide show
  1. package/README.md +5 -4
  2. package/data/snapshot.json +1 -0
  3. package/dist/catalog.d.ts +35 -39
  4. package/dist/catalog.js +112 -139
  5. package/dist/catalog.js.map +1 -1
  6. package/dist/cli.js +25 -16
  7. package/dist/cli.js.map +1 -1
  8. package/dist/http.js +1 -1
  9. package/dist/http.js.map +1 -1
  10. package/dist/index.d.ts +5 -7
  11. package/dist/index.js +4 -6
  12. package/dist/index.js.map +1 -1
  13. package/dist/server.d.ts +9 -7
  14. package/dist/server.js +14 -6
  15. package/dist/server.js.map +1 -1
  16. package/dist/snapshot.d.ts +8 -22
  17. package/dist/snapshot.js +41 -176
  18. package/dist/snapshot.js.map +1 -1
  19. package/dist/tools/index.d.ts +1 -1
  20. package/dist/tools/index.js.map +1 -1
  21. package/dist/tools/packages.js +49 -82
  22. package/dist/tools/packages.js.map +1 -1
  23. package/dist/tools/refine.d.ts +1 -2
  24. package/dist/tools/refine.js +90 -82
  25. package/dist/tools/refine.js.map +1 -1
  26. package/dist/tools/schema.d.ts +2 -1
  27. package/dist/tools/schema.js +9 -5
  28. package/dist/tools/schema.js.map +1 -1
  29. package/dist/tools/shared.d.ts +2 -2
  30. package/dist/types.d.ts +77 -64
  31. package/dist/types.js +6 -2
  32. package/dist/types.js.map +1 -1
  33. package/package.json +2 -2
  34. package/skills/vielzeug/SKILL.md +18 -20
  35. package/data/catalog.json +0 -2539
  36. package/data/llms-full.txt +0 -40978
  37. package/data/llms.txt +0 -60
  38. package/data/manifest.json +0 -4
  39. package/data/packages/archive.json +0 -87
  40. package/data/packages/arsenal.json +0 -270
  41. package/data/packages/assay.json +0 -52
  42. package/data/packages/atlas.json +0 -81
  43. package/data/packages/bard.json +0 -38
  44. package/data/packages/beacon.json +0 -51
  45. package/data/packages/clockwork.json +0 -69
  46. package/data/packages/codex.json +0 -37
  47. package/data/packages/coins.json +0 -99
  48. package/data/packages/conduit.json +0 -67
  49. package/data/packages/courier.json +0 -66
  50. package/data/packages/dnd.json +0 -60
  51. package/data/packages/familiar.json +0 -38
  52. package/data/packages/flux.json +0 -97
  53. package/data/packages/focus.json +0 -51
  54. package/data/packages/forge.json +0 -65
  55. package/data/packages/gesture.json +0 -65
  56. package/data/packages/herald.json +0 -80
  57. package/data/packages/illusionist.json +0 -132
  58. package/data/packages/ink.json +0 -41
  59. package/data/packages/keymap.json +0 -55
  60. package/data/packages/ledger.json +0 -60
  61. package/data/packages/lingua.json +0 -68
  62. package/data/packages/mesh.json +0 -52
  63. package/data/packages/necromancer.json +0 -55
  64. package/data/packages/orbit.json +0 -100
  65. package/data/packages/ore.json +0 -78
  66. package/data/packages/palette.json +0 -42
  67. package/data/packages/patchwork.json +0 -55
  68. package/data/packages/postmaster.json +0 -49
  69. package/data/packages/prism.json +0 -99
  70. package/data/packages/pulse.json +0 -71
  71. package/data/packages/refine.json +0 -36
  72. package/data/packages/ripple.json +0 -84
  73. package/data/packages/rune.json +0 -78
  74. package/data/packages/sandbox.json +0 -26
  75. package/data/packages/scout.json +0 -66
  76. package/data/packages/scribe.json +0 -57
  77. package/data/packages/scroll.json +0 -110
  78. package/data/packages/sentinel.json +0 -46
  79. package/data/packages/sigil.json +0 -52
  80. package/data/packages/sourcerer.json +0 -86
  81. package/data/packages/spell.json +0 -126
  82. package/data/packages/stage.json +0 -26
  83. package/data/packages/tabula.json +0 -39
  84. package/data/packages/tandem.json +0 -31
  85. package/data/packages/tavern.json +0 -34
  86. package/data/packages/tempo.json +0 -68
  87. package/data/packages/vault.json +0 -81
  88. package/data/packages/ward.json +0 -77
  89. package/data/packages/wayfinder.json +0 -126
  90. package/data/packages/wire.json +0 -51
  91. package/data/refine.json +0 -17277
  92. package/dist/consumer.d.ts +0 -17
  93. package/dist/consumer.js +0 -114
  94. package/dist/consumer.js.map +0 -1
  95. package/dist/port.d.ts +0 -2
  96. package/dist/port.js +0 -12
  97. package/dist/port.js.map +0 -1
@@ -1,41 +0,0 @@
1
- {
2
- "apiSource": "/**\n * @vielzeug/ink: freehand stroke smoothing, width profiling, and SVG path output.\n *\n * Pure, deterministic geometry functions. No DOM, no timers, no long-lived handles.\n */\nexport { InkConfigError, InkError } from './errors.js';\nexport { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';\nexport { simplifyStroke } from './simplify.js';\nexport { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';\nexport { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';\nexport { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';\nexport type { Point, StrokePoint } from './types.js';\nexport { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Ink: Freehand Stroke Geometry'\ndescription: Deterministic causal stroke stabilization, Catmull-Rom smoothing, speed and pressure width profiling, outline polygons, RDP simplification, and SVG path output.\npackage: ink\ncategory: data\nkeywords:\n [\n freehand,\n stroke,\n smoothing,\n catmull-rom,\n streamline,\n simplify,\n ramer-douglas-peucker,\n svg,\n path,\n variable-width,\n pressure,\n drawing,\n canvas,\n ]\nexports: [stabilizeStroke, smoothStroke, strokeWidths, strokeOutline, simplifyStroke, polylineToSvgPath]\nrelated: [gesture, prism]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"ink\" />\n\n## Why Ink?\n\nRaw pointer samples are jagged, and a good ink line needs stabilization, speed- and pressure-derived widths, a closed outline polygon, and a compact SVG path on top of them. Ink computes all four as pure, deterministic functions: identical samples always produce identical geometry, so strokes are replayable, testable, and server-renderable.\n\n```ts\n// Before\n// Hand-rolled filter math, per-point width heuristics, and manual path assembly\n// in every drawing surface, each with its own jitter and nondeterminism.\n\n// After\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';\n\nconst stabilized = stabilizeStroke(samples);\nconst d = polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 4 })), {\n close: true,\n});\n```\n\n| Feature | Ink | Ad-hoc smoothing | Sketch libraries |\n| ------------------------------ | -------------------------------------------- | ---------------- | -------------------- |\n| Bundle size | <PackageInfo package=\"ink\" type=\"size\" /> | n/a | Typically 10–50 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a | Varies |\n| Deterministic pure functions | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Rarely | Often randomized |\n| Variable-width outline polygon | Built in | Manual | Rare |\n| Runs without a DOM | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies | Usually browser-only |\n\n<div class=\"decision-callout\">\n\n**Use Ink when** a drawing or annotation surface needs reusable stroke geometry: stabilization, smoothing, width profiling, outlines, decimation, or SVG serialization without owning the math.\n\n**Consider direct polyline rendering when** the input is already clean (vector tools with their own smoothing) and a plain segment path is visually sufficient.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/ink\n```\n\n```sh [npm]\nnpm install @vielzeug/ink\n```\n\n```sh [yarn]\nyarn add @vielzeug/ink\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';\n\n// Raw samples from a pointer stream (see @vielzeug/gesture for capture),\n// timestamped with PointerEvent.timeStamp.\nconst samples = [\n { time: 0, x: 0, y: 0 },\n { time: 16, x: 12, y: 3 },\n { time: 32, x: 25, y: -2 },\n { time: 48, x: 40, y: 1 },\n];\n\nconst stabilized = stabilizeStroke(samples); // causal jitter removal\nconst widths = strokeWidths(stabilized, { width: 6 }); // speed-derived widths\nconst ring = strokeOutline(stabilized, widths); // closed variable-width polygon\nconst d = polylineToSvgPath(ring, { close: true }); // SVG `d` string\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `stabilizeStroke()`: causal Streamline-style averaging for live drawing; the stroke ends exactly where the pen lifted\n- `smoothStroke()`: deterministic Catmull-Rom resampling after capture\n- `strokeWidths()`: real-speed-derived widths (`distance / Δtime`) with pressure modulation and clamped scaling\n- `strokeOutline()`: closed variable-width polygon offset along local normals with capped ends; constant width with a single number\n- `simplifyStroke()`: iterative Ramer-Douglas-Peucker decimation preserving endpoints\n- `polylineToSvgPath()`: SVG `d` strings for open strokes and closed outline rings, with configurable precision\n- `InkError` / `InkConfigError`: typed configuration errors thrown at call time\n- Determinism: identical input always yields identical output; no randomness, no clocks\n- Zero runtime dependencies and no DOM requirement: works in Node, Workers, and SSR\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Gesture](/gesture/): captures the pointer samples Ink consumes; pan handles produce the raw point streams.\n- [Prism](/prism/): SVG rendering primitives; Ink's `d` strings drop straight into its path elements.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Ink: API Reference'\ndescription: 'API reference for @vielzeug/ink: causal stabilization, Catmull-Rom smoothing, speed-based widths, outline polygons, simplification, and SVG path output.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------- | -------------------------------------------------------- | --------- | ----------------------------------------------------------------- |\n| `stabilizeStroke()` | Causal jitter removal while drawing | Sync | One output point per input; last point snaps to the pen-up spot |\n| `smoothStroke()` | Catmull-Rom resampling after capture | Sync | Adds points: `steps` samples per input segment |\n| `strokeWidths()` | Per-point widths from real speed (`time`) and pressure | Sync | Velocity is off for the whole stroke if any point lacks `time` |\n| `strokeOutline()` | Closed variable-width polygon around a stroke | Sync | Array `widths` must match point count; a number is constant |\n| `simplifyStroke()` | Ramer-Douglas-Peucker decimation | Sync | Returns input references, not copies |\n| `polylineToSvgPath()` | SVG `d` string for polylines and closed outline rings | Sync | Requires at least one point; pass `close: true` for rings |\n| `InkError` | Base class for all ink errors | Sync | Narrow with `instanceof InkError` |\n| `InkConfigError` | Invalid options or point counts | Sync | Thrown at call time, not construction |\n| `Point` / `StrokePoint` | Structural point shapes shared across the canvas toolkit | Sync | `pressure` and `time` are optional; `time` unlocks width velocity |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------- | ---------------------------------------------------------------------------------------------------- |\n| `@vielzeug/ink` | Stabilization, smoothing, width profiling, outline, simplification, SVG serialization, types, errors |\n\n---\n\n## Core Functions\n\n### `stabilizeStroke()`\n\n```ts\nfunction stabilizeStroke(points: readonly StrokePoint[], options?: StabilizeStrokeOptions): StrokePoint[];\n```\n\nRemoves hand jitter _while the stroke is being drawn_: a causal exponential average toward each incoming sample with a jitter dead zone, so straight lines stay crisp. It never looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ----------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Input samples |\n| `options` | `StabilizeStrokeOptions` | `strength` in `[0, 1]`; `0` is the raw input, default `0.5` |\n\n**Returns:** New `StrokePoint[]` with exactly the input's length. The last point is the last input point exactly — the stroke ends where the pen lifted. Inside the dead zone the position repeats but the incoming sample's `pressure` and `time` carry through.\n\n**Example**\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.6 });\n```\n\nThrows `InkConfigError` for a `strength` outside `[0, 1]`.\n\n---\n\n### `smoothStroke()`\n\n```ts\nfunction smoothStroke(points: readonly StrokePoint[], options?: SmoothStrokeOptions): StrokePoint[];\n```\n\nResamples a stroke through a uniform Catmull-Rom spline: `steps` samples per input segment, with the first and last input points preserved exactly. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input. For jitter removal while drawing, use `stabilizeStroke()` instead — this function adds points and looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ------------------------------------------------------------------------------ |\n| `points` | `readonly StrokePoint[]` | Input samples; fewer than three are returned as copies |\n| `options` | `SmoothStrokeOptions` | `tension` in `[0, 1]` (default `1`), `steps` integer `[2, 1000]` (default `8`) |\n\n**Returns:** New `StrokePoint[]` with `steps` samples per input segment plus the exact final point.\n\n**Example**\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\nThrows `InkConfigError` for a `tension` outside `[0, 1]` or a `steps` value outside `[2, 1000]` or non-integer.\n\n---\n\n### `strokeWidths()`\n\n```ts\nfunction strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];\n```\n\nReturns one width per point from real pen speed and optional pressure. Speed is `distance / Δtime` between consecutive points, which stays correct after any stabilization, smoothing, or simplification. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale. When any point lacks `time` — or a Δtime is zero — velocity modulation is disabled for the whole stroke (width becomes `width × pressure`) instead of guessing speed from sample spacing.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `options` | `StrokeWidthOptions` | `width` (required, > 0), `thinning` in `[0, 1]` (default `0.5`), `referenceSpeed` in px/ms (default `0.5`), `taper`, `simulatePressure` |\n\n**Returns:** `number[]` with the same length as `points`. The first point uses the forward segment; degenerate (zero-length) segments keep the previous scale so stationary samples do not spike.\n\nPressure multiplies the result through a curve where `0.5` (the neutral value a mouse reports) maps to exactly `1`: the range is `[0.5, 1.25]`, so a neutral-pressure stroke is as wide as one without pressure data.\n\n`taper` fades the width in over `taper.start` and out over `taper.end` units of arc length (same units as `width`): a smoothstep ramp from a `0.15` floor at the tip to full width at the taper length, multiplied on top of the speed/pressure profile. `simulatePressure` (default `false`) synthesizes pressure for points that have none on a timed stroke: the width multiplier ramps from `0.5` at each tip to neutral across the first and last 15% of arc length, so mouse strokes thin at the ends. Points that carry real `pressure` always use it, and untimed strokes ignore the option.\n\n**Example**\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(samples, { width: 6, thinning: 0.5 });\nconst tapered = strokeWidths(samples, { width: 6, taper: { start: 30, end: 30 }, simulatePressure: true });\n```\n\nThrows `InkConfigError` for a non-positive `width` or `referenceSpeed`, a `thinning` outside `[0, 1]`, a negative or non-finite `taper` length, or an empty `points` array.\n\n---\n\n### `strokeOutline()`\n\n```ts\nfunction strokeOutline(\n points: readonly StrokePoint[],\n widths: number | readonly number[],\n options?: StrokeOutlineOptions,\n): Point[];\n```\n\nReturns a closed polygon approximating the variable-width stroke: start cap, left offsets forward, end cap, right offsets backward, with no repeated final vertex. Pass a constant `widths` number for a uniform stroke.\n\n| Parameter | Type | Description |\n| --------- | ----------------------------- | --------------------------------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `widths` | `number \\| readonly number[]` | Constant width, or per-point widths from `strokeWidths()` |\n| `options` | `StrokeOutlineOptions` | `cap` (default `'round'`), `join` (default `'round'`), `miterLimit` (default `4`) |\n\n`cap` selects the end treatment: `'round'` half-circle caps, `'butt'` no cap points, `'square'` a half-width tangent extension at each end. `join` handles turns sharper than 90°, where naive offsetting makes the inner side cross itself: `'round'` keeps the plain offset samples (current default output), `'bevel'` replaces each sharp joint with the two adjacent segment-offset points, dropping the crossing spike, and `'miter'` extends to the offset-line intersection while the miter length stays within `miterLimit` × half width, falling back to bevel beyond it.\n\n**Returns:** `Point[]` ring, deterministic for deterministic input.\n\n**Example**\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(samples, widths);\nconst uniform = strokeOutline(samples, 4);\nconst marker = strokeOutline(samples, 4, { cap: 'square', join: 'miter', miterLimit: 6 });\n```\n\nThrows `InkConfigError` when an array `widths` length differs from `points` length or any width is not a positive finite number, when `cap` or `join` is not a known variant, or when `miterLimit` is not a positive finite number.\n\n---\n\n### `simplifyStroke()`\n\n```ts\nfunction simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[];\n```\n\nReturns a Ramer-Douglas-Peucker decimated subsequence of the input; first and last points are always kept.\n\n| Parameter | Type | Description |\n| ----------- | ------------------------ | -------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples |\n| `tolerance` | `number` | Maximum perpendicular deviation to discard, `>= 0` |\n\n**Returns:** `StrokePoint[]` containing the same object references as the input (metadata such as `pressure` and `time` survives).\n\n**Example**\n\n```ts\nimport { simplifyStroke } from '@vielzeug/ink';\n\nconst decimated = simplifyStroke(samples, 0.5);\n```\n\nThrows `InkConfigError` for a negative or non-finite `tolerance`.\n\n---\n\n### `polylineToSvgPath()`\n\n```ts\nfunction polylineToSvgPath(points: readonly Point[], options?: PolylineToSvgPathOptions): string;\n```\n\nReturns an SVG path `d` string: `M x y` plus one `L x y` per remaining point. Works for open strokes and for the closed ring from `strokeOutline()` — pass `close: true` for rings.\n\n| Parameter | Type | Description |\n| --------- | -------------------------- | --------------------------------------------------------------------------- |\n| `points` | `readonly Point[]` | Stroke samples or ring vertices (at least one) |\n| `options` | `PolylineToSvgPathOptions` | `close` appends `Z`; `precision` rounds coordinates (`0`–`12`, default `2`) |\n\n**Returns:** `string` suitable for a `<path d=\"...\">` attribute.\n\n**Example**\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst d = polylineToSvgPath(samples, { precision: 1 }); // \"M 0 0 L 12 3 L 25 -2\"\nconst outline = polylineToSvgPath(ring, { close: true }); // \"M ... L ... Z\"\n```\n\nThrows `InkConfigError` when `points` is empty or `precision` is out of range.\n\n## Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\n```\n\nA two-dimensional point. Structural so canvas-toolkit packages can share it without importing each other.\n\n```ts\ntype StrokePoint = Readonly<{\n x: number;\n y: number;\n pressure?: number; // normalized [0, 1]; 0.5 is neutral\n time?: number; // milliseconds, e.g. PointerEvent.timeStamp; enables width velocity\n}>;\n```\n\nA sampled stroke point. `time` values only need to share a clock; any monotonic source works.\n\n```ts\ninterface StabilizeStrokeOptions {\n strength?: number; // [0, 1], default 0.5\n}\n```\n\n```ts\ninterface SmoothStrokeOptions {\n tension?: number; // [0, 1], default 1\n steps?: number; // [2, 1000] integer, default 8\n}\n```\n\n```ts\ninterface StrokeWidthOptions {\n width: number; // required, > 0\n thinning?: number; // [0, 1], default 0.5\n referenceSpeed?: number; // > 0, default 0.5 (px per ms)\n taper?: StrokeTaperOptions; // arc-length end fade, default none\n simulatePressure?: boolean; // default false; timed strokes only\n}\n```\n\n```ts\ninterface StrokeTaperOptions {\n start?: number; // fade-in length along arc length, >= 0, default 0\n end?: number; // fade-out length along arc length, >= 0, default 0\n}\n```\n\n```ts\ntype StrokeCap = 'round' | 'butt' | 'square';\n```\n\n```ts\ntype StrokeJoin = 'round' | 'bevel' | 'miter';\n```\n\n```ts\ninterface StrokeOutlineOptions {\n cap?: StrokeCap; // default 'round'\n join?: StrokeJoin; // default 'round'\n miterLimit?: number; // > 0, default 4 (miter length / half width)\n}\n```\n\n```ts\ninterface PolylineToSvgPathOptions {\n close?: boolean; // default false\n precision?: number; // [0, 12] integer, default 2\n}\n```\n\n## Errors\n\n| Error | Trigger |\n| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |\n| `InkError` | Base class; catch all ink errors with `instanceof InkError` |\n| `InkConfigError` | Invalid options (strength, tension, steps, width, thinning, precision, tolerance, cap, join, miterLimit, taper, …) or point-count mismatches |\n",
6
- "usage": "---\ntitle: 'Ink: Usage Guide'\ndescription: 'How to smooth freehand strokes with @vielzeug/ink: stabilization, smoothing, speed-based widths, outline polygons, and SVG paths.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nCapture samples from any pointer source — with a timestamp — then run them through the pipeline: stabilize while drawing, simplify, width, outline, serialize. Every function is pure, so you can call them in any order and re-run them freely.\n\n```ts\nimport {\n polylineToSvgPath,\n simplifyStroke,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\n// Capture: PointerEvent.timeStamp is the timestamp ink wants.\nconst samples: StrokePoint[] = [];\nelement.addEventListener('pointermove', (event) => {\n samples.push({ pressure: event.pressure, time: event.timeStamp, x: event.offsetX, y: event.offsetY });\n});\n\nconst stabilized = stabilizeStroke(samples);\nconst widths = strokeWidths(stabilized, { width: 6 });\nconst d = polylineToSvgPath(strokeOutline(stabilized, widths), { close: true });\n\n// Render with any SVG-capable surface.\nconst path = document.createElementNS('http://www.w3.org/2000/svg', 'path');\npath.setAttribute('d', d);\n```\n\n## Stabilize While Drawing\n\n`stabilizeStroke()` removes hand jitter causally — it never looks ahead — so you can run it on every pointer move while the stroke is being drawn. It emits exactly one point per input sample, keeping per-sample metadata aligned, and its last point is always the last input point: the stroke ends exactly where the pen lifted.\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.5 }); // 0 = raw, 1 = maximum smoothing\n```\n\n## Smooth After Capture\n\n`smoothStroke()` resamples the stroke through a uniform Catmull-Rom spline: each input segment becomes `steps` samples, and the first and last input points are preserved exactly. Use it after capture when you want extra curvature between sparse samples. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input.\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\n## Profile Widths From Speed and Pressure\n\n`strokeWidths()` derives real pen speed from the `time` field: `distance / Δtime` between consecutive points. That stays correct after any stabilization, smoothing, or simplification — pipeline order no longer matters. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(stabilized, {\n width: 6,\n thinning: 0.5, // 0 disables velocity, 1 is fully inverse-proportional\n referenceSpeed: 0.5, // neutral pen speed in pixels per millisecond\n});\n```\n\nWhen points carry `pressure` (normalized `[0, 1]`), it multiplies the result: `0.5` is neutral and maps to exactly `1`, so a mouse (which reports `0.5`) draws as wide as a device without pressure data. When any point lacks `time`, velocity modulation is disabled for the whole stroke — width becomes `width × pressure` — instead of guessing speed from sample spacing.\n\n`taper` fades the ends: within the first `taper.start` and last `taper.end` units of arc length, the width is multiplied by a smoothstep ramp that bottoms out at `0.15` of full width at the tips. `simulatePressure` gives mouse strokes the same in/out feel by synthesizing pressure for points that have none (ramping to `0.5×` width at each tip over the last 15% of arc length); points with real `pressure` always keep it.\n\n```ts\nconst tapered = strokeWidths(stabilized, {\n width: 6,\n taper: { start: 40, end: 40 }, // 40 px of arc length faded at each end\n simulatePressure: true, // thin the ends of pressure-less mouse strokes\n});\n```\n\n## Build the Outline\n\n`strokeOutline()` offsets each sample by half its width along the local normal and closes the ring with half-circle caps at both ends. The result is a plain `Point[]` you can fill with any renderer.\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(stabilized, widths); // variable width, closed polygon\nconst uniform = strokeOutline(stabilized, 6); // constant width, no array needed\n```\n\n`cap` changes the ends: `'butt'` stops at the last offsets, `'square'` extends each end by half the width along the tangent. `join` fixes the crossing spike naive offsetting produces at turns sharper than 90°: `'bevel'` cuts the corner with the two adjacent offset points, and `'miter'` extends to the exact intersection while its length stays within `miterLimit` × half width, falling back to bevel beyond that.\n\n```ts\nconst marker = strokeOutline(stabilized, 6, { cap: 'square', join: 'miter', miterLimit: 6 });\n```\n\n## Simplify Before Serializing\n\nLong strokes accumulate samples. `simplifyStroke()` runs Ramer-Douglas-Peucker and returns a subsequence of the input, so object identity, `pressure`, and `time` survive. Apply it to the outline before emitting SVG to shrink path data.\n\n```ts\nimport { simplifyStroke, polylineToSvgPath } from '@vielzeug/ink';\n\nconst compact = polylineToSvgPath(simplifyStroke(ring, 0.25), { close: true });\n```\n\n## Serialize to SVG Paths\n\n`polylineToSvgPath()` writes `M` plus one `L` per point, rounding coordinates to `precision` decimal places. Pass `close: true` to append `Z` for the closed outline ring; leave it off for a centerline path.\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst centerline = polylineToSvgPath(simplifyStroke(stabilized, 0.5), { precision: 1 });\nconst outline = polylineToSvgPath(ring, { close: true });\n```\n\n## Framework Integration\n\nInk functions are pure, so they memoize cleanly. Recompute geometry only when the sample array changes.\n\n::: code-group\n\n```tsx [React]\nimport { useMemo } from 'react';\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths, type StrokePoint } from '@vielzeug/ink';\n\nfunction InkPath({ samples }: { samples: StrokePoint[] }) {\n const d = useMemo(() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n }, [samples]);\n\n return <path d={d} />;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { computed } from 'vue';\nimport {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\nconst props = defineProps<{ samples: StrokePoint[] }>();\nconst d = computed(() => {\n const stabilized = stabilizeStroke(props.samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n});\n</script>\n\n<template>\n <svg><path :d=\"d\" /></svg>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n } from '@vielzeug/ink';\n\n export let samples: StrokePoint[];\n $: d = (() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n })();\n</script>\n\n<svg><path {d} /></svg>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nGesture produces the raw samples: bind a pan or drag handle, append each `current` point (with `event.timeStamp`) to an array, and pass the array to Ink when the stroke ends. Prism (or any SVG renderer) consumes the `d` strings Ink returns.\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\nimport { polylineToSvgPath, stabilizeStroke, type StrokePoint } from '@vielzeug/ink';\n\nconst samples: StrokePoint[] = [];\nconst drag = createDragGesture(surface, {\n onMove: ({ currentX, currentY, event }) => samples.push({ time: event.timeStamp, x: currentX, y: currentY }),\n onEnd: () => {\n path.setAttribute('d', polylineToSvgPath(stabilizeStroke(samples), { precision: 1 }));\n },\n});\n```\n\n## Best Practices\n\n- Pass `time` on every sample (`PointerEvent.timeStamp` or `performance.now()`): without it, widths are pressure-only and speed information is thrown away.\n- Stabilize live, smooth once: run `stabilizeStroke()` per pointer move for a calm preview, and add `smoothStroke()` or `simplifyStroke()` at commit time.\n- Simplify outlines with a tolerance around `0.2`–`0.5` device pixels; larger tolerances visibly flatten caps.\n- Keep `precision` at `1`–`2` for display paths; raise it only when another tool re-processes the output.\n- Treat invalid options errors (`InkConfigError`) as programming bugs: they throw at call time with the offending option named.\n- Memoize per stroke in UI frameworks; the functions are pure and cheap to cache.\n",
7
- "examples": "---\ntitle: 'Ink: Examples'\ndescription: Practical examples and recipes for @vielzeug/ink.\n---\n\n## Examples\n\n- [Jitter-Free Ink](./examples/jitter-free-ink.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "ink-outline-options",
12
- "code": "import { polylineToSvgPath, strokeOutline, strokeWidths } from '@vielzeug/ink'\n\n// A hairpin turn plus a straight run: sharp enough that naive offsets spike.\nconst samples = [\n { time: 0, x: 20, y: 40 },\n { time: 16, x: 150, y: 40 },\n { time: 32, x: 70, y: 110 },\n { time: 48, x: 60, y: 30 },\n]\n\nconst widths = strokeWidths(samples, {\n width: 14,\n taper: { start: 30, end: 30 }, // fade the ends over 30px of arc length\n simulatePressure: true, // mouse strokes have no pressure: synthesize it\n})\n\nconst variants = [\n { label: 'round join + round cap', options: {} },\n { label: 'bevel join + butt cap', options: { cap: 'butt', join: 'bevel' } },\n { label: 'miter join + square cap', options: { cap: 'square', join: 'miter', miterLimit: 6 } },\n]\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 320 260')\nsvg.style.cssText = 'width:100%;max-width:480px;background:#f8fafc;border-radius:12px;'\n\nvariants.forEach((variant, row) => {\n const outline = strokeOutline(samples, widths, variant.options)\n const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')\n path.setAttribute('d', polylineToSvgPath(outline, { close: true }))\n path.setAttribute('fill', '#0f172a')\n path.setAttribute('transform', `translate(0 ${row * 84})`)\n const label = document.createElementNS('http://www.w3.org/2000/svg', 'text')\n label.setAttribute('x', '8')\n label.setAttribute('y', 12 + row * 84)\n label.setAttribute('font-size', '10')\n label.setAttribute('fill', '#64748b')\n label.textContent = variant.label\n svg.append(label, path)\n console.log(variant.label, 'outline points:', outline.length)\n})\n\ndocument.body.appendChild(svg)",
13
- "name": "strokeOutline options - caps, joins, and taper"
14
- },
15
- {
16
- "id": "ink-smoothing",
17
- "code": "import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink'\n\n// Deterministic zig-zag samples with timestamps: the jitter stabilization must remove.\nconst samples = Array.from({ length: 24 }, (_, i) => ({\n time: i * 16,\n x: 20 + i * 12,\n y: 80 + (i % 2 === 0 ? 14 : -14),\n}))\n\nconst stabilized = stabilizeStroke(samples)\nconst widths = strokeWidths(stabilized, { width: 8 })\nconst outline = strokeOutline(stabilized, widths)\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 320 160')\nsvg.style.cssText = 'width:100%;max-width:480px;background:#f8fafc;border-radius:12px;'\n\nconst raw = document.createElementNS('http://www.w3.org/2000/svg', 'polyline')\nraw.setAttribute('points', samples.map((p) => `${p.x},${p.y}`).join(' '))\nraw.setAttribute('fill', 'none')\nraw.setAttribute('stroke', '#cbd5e1')\nraw.setAttribute('stroke-dasharray', '4 4')\n\nconst ink = document.createElementNS('http://www.w3.org/2000/svg', 'path')\nink.setAttribute('d', polylineToSvgPath(outline, { close: true }))\nink.setAttribute('fill', '#0f172a')\n\nsvg.append(raw, ink)\ndocument.body.appendChild(svg)\n\nconsole.log('samples:', samples.length, 'stabilized:', stabilized.length, 'outline points:', outline.length)",
18
- "name": "stabilizeStroke - Jitter-free ink"
19
- }
20
- ],
21
- "typeSignatures": {
22
- "InkConfigError": "export { InkConfigError, InkError } from './errors.js';",
23
- "InkError": "export { InkConfigError, InkError } from './errors.js';",
24
- "StrokeCap": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
25
- "StrokeJoin": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
26
- "StrokeOutlineOptions": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
27
- "strokeOutline": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
28
- "simplifyStroke": "export { simplifyStroke } from './simplify.js';",
29
- "SmoothStrokeOptions": "export { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';",
30
- "smoothStroke": "export { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';",
31
- "StabilizeStrokeOptions": "export { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';",
32
- "stabilizeStroke": "export { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';",
33
- "PolylineToSvgPathOptions": "export { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';",
34
- "polylineToSvgPath": "export { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';",
35
- "Point": "export type { Point, StrokePoint } from './types.js';",
36
- "StrokePoint": "export type { Point, StrokePoint } from './types.js';",
37
- "StrokeTaperOptions": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';",
38
- "StrokeWidthOptions": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';",
39
- "strokeWidths": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';"
40
- }
41
- }
@@ -1,55 +0,0 @@
1
- {
2
- "apiSource": "// Core API: most users only need these\nexport type { ConflictOptions } from './conflicts';\nexport { findShortcutConflicts } from './conflicts';\nexport { KeymapConfigError, KeymapError, KeymapParseError } from './errors';\nexport { formatShortcut, formatShortcutParts } from './format';\nexport { createKeymap } from './keymap';\nexport { detectModKey, matchKey } from './parser';\nexport type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Keymap: Headless keyboard shortcut manager'\ndescription: Target-local keyboard shortcut manager with chords, event-aware guards, modifier aliases, and terminal disposal.\npackage: keymap\ncategory: app-infrastructure\nkeywords: [keyboard, shortcuts, hotkeys, chord, keybinding, headless, accessibility]\nexports:\n [\n createKeymap,\n findShortcutConflicts,\n formatShortcut,\n matchKey,\n detectModKey,\n KeymapConfigError,\n KeymapError,\n KeymapParseError,\n ]\nrelated: [herald, refine, ore]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"keymap\" />\n\n## Why Keymap?\n\nBrowser keyboard handling needs modifier normalization, chord state, context policy, and listener ownership. Keymap keeps those concerns in one headless, zero-dependency handle.\n\n```ts\n// Before\nwindow.addEventListener('keydown', (event) => {\n if ((event.ctrlKey || event.metaKey) && event.key === 's') event.preventDefault();\n});\n\n// After\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst map = createKeymap([{ id: 'save', shortcut: 'mod+s', handler: () => console.log('save') }]);\nconst unmount = map.mount(document);\n\nunmount();\nmap.dispose();\n```\n\n| Feature | Raw `addEventListener` | Keymap |\n| ------------------- | -------------------------------------------- | ----------------------------------------------------------------- |\n| Bundle size | 0 B (built-in) | <PackageInfo package=\"keymap\" type=\"size\" /> |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Chord sequences | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Modifier aliases | <ore-icon name=\"x\" size=\"16\"></ore-icon> | `cmd`, `win`, `option` → canonical |\n| Context guards | Manual `if` in handler | Event-aware `when(event)` predicate |\n| Chord ownership | Application-managed state | Per mounted target |\n| Per-binding control | Manual `preventDefault`/`stopPropagation` | Per-binding `preventDefault`/`stopPropagation` with safe defaults |\n| Disposable | Manual `removeEventListener` | Terminal `dispose()` + `[Symbol.dispose]()` |\n\n<div class=\"decision-callout\">\n\n**Use Keymap when** you need chord sequences (`g g`, `ctrl+k ctrl+s`), modifier aliases, or context-scoped hotkeys that can be cleanly mounted and unmounted.\n\n**Consider raw `addEventListener` when** you have a single, static, never-removed hotkey and don't need chords.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/keymap\n```\n\n```sh [npm]\nnpm install @vielzeug/keymap\n```\n\n```sh [yarn]\nyarn add @vielzeug/keymap\n```\n\n:::\n\n## Quick Start\n\nCreate, mount, then dispose one map owned by your UI scope.\n\n```ts\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst map = createKeymap([\n { id: 'save', shortcut: 'mod+k mod+s', handler: () => console.log('save') },\n { id: 'palette', shortcut: 'mod+shift+p', handler: () => console.log('open palette') },\n { id: 'top', shortcut: 'g g', handler: () => window.scrollTo({ top: 0 }) },\n { id: 'close', shortcut: 'escape', handler: () => console.log('close panel') },\n]);\n\nconst unmount = map.mount(document);\n\nunmount();\nmap.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createKeymap()`: Create a keymap from an ordered binding array; mount to any `EventTarget`\n- Chord sequences: `\"g g\"`, `\"ctrl+k ctrl+s\"` with configurable timeout (default 1 s)\n- Modifier aliases: `cmd`/`command`/`win` → `meta`; `opt`/`option` → `alt`; `mod` → platform-aware\n- `Binding` objects: each binding has an explicit `id`, `shortcut`, `handler`, and optional `trigger`, `when`, `preventDefault`, `stopPropagation`\n- Per-binding `preventDefault`/`stopPropagation`: safe defaults (`true`/`false`) applied to completed shortcuts and intermediate chord steps\n- `tap()`: observe chord progress, timeout, matches, and disposal without changing behavior\n- `modKey` option: explicit platform override for SSR and cross-platform tests\n- `formatShortcut()`: platform-aware display (`⇧⌘P` on Mac, `Ctrl+Shift+P` elsewhere)\n- `@vielzeug/keymap/parse` subpath: `parseShortcut()`, `parseStep()`, `matchStep()`, `matchKey()`, `canonicalizeShortcut()`, `detectModKey()` for custom tooling\n- `listBindings()`: snapshot all active bindings (id, shortcut, trigger, preventDefault, stopPropagation) for palette UIs\n- `findShortcutConflicts()`: detect prefix/duplicate conflicts before binding a user-customized shortcut\n- Disposable: `dispose()` + `[Symbol.dispose]` for `using` declarations\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Herald](/herald/): Typed event bus; pair with Keymap by publishing shortcut events to a bus instead of calling handlers directly\n- [Refine](/refine/): `ore-command-palette` uses Keymap internally; register your own shortcuts alongside it\n- [Ore](/ore/): Attach a keymap inside a `define()` setup function for component-scoped shortcuts\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Keymap: API Reference'\ndescription: Complete API reference for @vielzeug/keymap bindings, chords, parsing, formatting, and lifecycle.\n---\n\n[[toc]]\n\n## API Overview\n\n### Core API (Most Users)\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------- | ----------------------------------------------------------------------------------------------- | -------------- | --------------------------------------------------------------- |\n| `createKeymap()` | Create shortcut manager from an ordered binding array | Sync | `dispose()` is terminal |\n| `findShortcutConflicts()` | Find duplicate and prefix paths | Sync | Invalid non-empty input throws |\n| `formatShortcut()` | Format shortcut labels | Sync | Invalid input returns `''` |\n| `matchKey()` | Match an event against one shortcut pattern | Sync | Unparseable pattern returns `false`; chord patterns never match |\n| `detectModKey()` | Resolve platform primary modifier | Sync | Returns `ctrl` without `navigator` |\n| `tap()` | Observe chord lifecycle, matches, and disposal | Sync | Observer failures are swallowed |\n| `Binding` | Per-binding config type (id, shortcut, handler, trigger, when, preventDefault, stopPropagation) | N/A | Reusing an `id` replaces its binding |\n\n### Parser Subpath (`@vielzeug/keymap/parse`)\n\nUse the parser subpath if you're building keyboard-aware config validators, custom UI, or framework integrations.\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------ | --------------------------------- | -------------- | ---------------------------------- |\n| `parseShortcut()` | Strictly parse full shortcut | Sync | Empty input throws |\n| `parseStep()` | Parse one step without throwing | Sync | Invalid input returns `null` |\n| `canonicalizeShortcut()` | Create stable shortcut key | Sync | Input must already be parsed |\n| `matchStep()` | Test event against parsed step | Sync | Extra modifiers prevent a match |\n| `detectModKey()` | Resolve platform primary modifier | Sync | Returns `ctrl` without `navigator` |\n\n### Errors\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------- | ----------------------------- | -------------- | -------------------------------------------- |\n| `KeymapError` | Base Keymap error | Sync | Includes parse, config, and lifecycle errors |\n| `KeymapConfigError` | Invalid `createKeymap` option | Sync | Thrown for a non-positive `chordTimeout` |\n| `KeymapParseError` | Strict parser error | Sync | `parseStep()` never throws it |\n\n## Package Entry Points\n\n| Import | Purpose |\n| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/keymap` | Root entry point for `createKeymap`, `formatShortcut`, `findShortcutConflicts`, `matchKey`, `detectModKey`, errors, and public types. |\n| `@vielzeug/keymap/parse` | Parser internals subpath for custom tooling: `parseShortcut`, `parseStep`, `matchStep`, `matchKey`, `canonicalizeShortcut`, `detectModKey`. |\n\n## Core Manager\n\n### `createKeymap()`\n\n```ts\nfunction createKeymap(bindings?: readonly Binding[], options?: KeymapOptions): Keymap;\n```\n\nCreates shortcut manager with independent chord state for each mounted target.\n\n| Parameter | Type | Description |\n| ---------- | -------------------- | ---------------------------------------------------------------------------------------- |\n| `bindings` | `readonly Binding[]` | Ordered array of bindings. Each binding has an explicit `id`, `shortcut`, and `handler`. |\n| `options` | `KeymapOptions` | Chord, modifier, and global-guard configuration. |\n\n**Returns:** `Keymap`.\n\n```ts\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst map = createKeymap([{ id: 'save', shortcut: 'ctrl+s', handler: () => console.log('save') }]);\nconst unmount = map.mount(document);\n\nunmount();\nmap.dispose();\n```\n\n| `Keymap` member | Return | Contract |\n| ------------------------ | ------------------------- | --------------------------------------------------------------------------------------------------- |\n| `bind(binding)` | `() => void` | Adds or replaces a binding with the same `id`. Returned callback removes that binding while active. |\n| `mount(target)` | `() => void` | Adds target listener. Repeat mounts of same target are reference-counted. |\n| `unbind(id)` | `void` | Removes binding by id. Warns in development when unknown. |\n| `listBindings()` | `readonly BindingEntry[]` | Returns a detached binding snapshot. |\n| `tap(handler, options?)` | `() => void` | Observes chord lifecycle, matches, and disposal. Supports signal-owned teardown. |\n| `dispose()` | `void` | Removes all listeners, aborts signal, and permanently disposes map. Idempotent. |\n| `disposed` | `boolean` | `true` after first `dispose()`. |\n| `disposalSignal` | `AbortSignal` | Aborts when map is disposed. |\n| `[Symbol.dispose]()` | `void` | Calls `dispose()`. |\n\nAfter disposal, `bind()`, `unbind()`, and `mount()` throw `KeymapError`.\n\n## Runtime Observation\n\n### `tap()`\n\n```ts\nfunction tap(handler: (event: KeymapEvent) => void, options?: { signal?: AbortSignal }): () => void;\n```\n\nObserves chord progress, cancellation, completed matches, timeouts, and disposal without affecting shortcut behavior.\n\n| Parameter | Type | Description |\n| ---------------- | ------------------------------ | ---------------------------------------------------------------- |\n| `handler` | `(event: KeymapEvent) => void` | Receives each runtime event synchronously. Errors are swallowed. |\n| `options.signal` | `AbortSignal` | Detaches the handler when aborted. |\n\n**Returns:** An idempotent detach function.\n\n```ts\nconst stop = map.tap((event) => {\n if (event.type === 'chord-start') showChordHint(event.step);\n if (event.type === 'chord-cancel' || event.type === 'chord-timeout' || event.type === 'match') hideChordHint();\n});\n```\n\n## Conflict Analysis\n\n### `findShortcutConflicts()`\n\n```ts\nfunction findShortcutConflicts(\n shortcut: string,\n entries: readonly BindingEntry[],\n options?: ConflictOptions,\n): BindingEntry[];\n```\n\nReturns entries with same-trigger exact or prefix-conflicting shortcut paths.\n\n| Parameter | Type | Description |\n| ---------- | ------------------------- | ----------------------------------------------------------------------- |\n| `shortcut` | `string` | Proposed shortcut. Empty or whitespace-only input returns no conflicts. |\n| `entries` | `readonly BindingEntry[]` | Bindings to compare, commonly `map.listBindings()`. |\n| `options` | `ConflictOptions` | Optional modifier resolution and trigger filter. |\n\n**Returns:** Matching entries. Returns `[]` when no conflict exists.\n\n```ts\nimport { createKeymap, findShortcutConflicts } from '@vielzeug/keymap';\n\nconst map = createKeymap([{ id: 'top', shortcut: 'g', handler: () => console.log('top') }]);\nconst conflicts = findShortcutConflicts('g g', map.listBindings());\n\nconsole.log(conflicts.length); // 1\n```\n\n## Formatting\n\n### `formatShortcut()`\n\n```ts\nfunction formatShortcut(shortcut: string, modKey?: 'ctrl' | 'meta'): string;\n```\n\nFormats parsed shortcut into Mac symbols for `meta` or word labels for `ctrl`.\n\n| Parameter | Type | Description |\n| ---------- | ------------------ | -------------------------------------------------------- |\n| `shortcut` | `string` | Shortcut string to format. |\n| `modKey` | `'ctrl' \\| 'meta'` | Platform primary modifier. Defaults to `detectModKey()`. |\n\n**Returns:** Display label, or `''` for invalid input.\n\n```ts\nimport { formatShortcut } from '@vielzeug/keymap';\n\nformatShortcut('mod+shift+p', 'meta'); // ⇧⌘P\nformatShortcut('mod+shift+p', 'ctrl'); // Ctrl+Shift+P\n```\n\n## Parser Subpath (`@vielzeug/keymap/parse`)\n\n### `parseShortcut()`\n\n```ts\nfunction parseShortcut(raw: string, modKey?: 'ctrl' | 'meta'): Shortcut;\n```\n\nStrictly parses one or more space-separated shortcut steps.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | -------------------------------------------------------- |\n| `raw` | `string` | Full shortcut string. |\n| `modKey` | `'ctrl' \\| 'meta'` | Platform primary modifier. Defaults to `detectModKey()`. |\n\n**Returns:** Parsed `Shortcut`.\n\n```ts\nimport { parseShortcut } from '@vielzeug/keymap/parse';\n\nconst shortcut = parseShortcut('ctrl+k ctrl+s', 'ctrl');\nconsole.log(shortcut.length); // 2\n```\n\nThrows `KeymapParseError` for empty, modifier-only, or ambiguous steps.\n\n---\n\n### `parseStep()`\n\n```ts\nfunction parseStep(raw: string, modKey?: 'ctrl' | 'meta'): ShortcutStep | null;\n```\n\nParses one shortcut step without throwing.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | -------------------------------------------------------- |\n| `raw` | `string` | One shortcut step. |\n| `modKey` | `'ctrl' \\| 'meta'` | Platform primary modifier. Defaults to `detectModKey()`. |\n\n**Returns:** Parsed `ShortcutStep`, or `null` for empty, modifier-only, or ambiguous input.\n\n```ts\nimport { parseStep } from '@vielzeug/keymap/parse';\n\nparseStep('ctrl+k', 'ctrl'); // { key: 'k', modifiers: Set(['ctrl']) }\nparseStep('ctrl+k+j', 'ctrl'); // null\n```\n\n---\n\n### `canonicalizeShortcut()`\n\n```ts\nfunction canonicalizeShortcut(steps: readonly ShortcutStep[]): string;\n```\n\nConverts parsed steps into stable canonical string with sorted modifier order.\n\n| Parameter | Type | Description |\n| --------- | ------------------------- | ---------------------- |\n| `steps` | `readonly ShortcutStep[]` | Parsed shortcut steps. |\n\n**Returns:** Canonical shortcut string.\n\n```ts\nimport { canonicalizeShortcut, parseShortcut } from '@vielzeug/keymap/parse';\n\ncanonicalizeShortcut(parseShortcut('shift+ctrl+k', 'ctrl')); // ctrl+shift+k\n```\n\n---\n\n### `matchStep()`\n\n```ts\nfunction matchStep(event: KeyboardEvent, step: ShortcutStep): boolean;\n```\n\nTests exact key and modifier equality for one parsed step.\n\n| Parameter | Type | Description |\n| --------- | --------------- | ------------------------------------------------------ |\n| `event` | `KeyboardEvent` | Event to match. Missing runtime `key` returns `false`. |\n| `step` | `ShortcutStep` | Parsed step. |\n\n**Returns:** `true` only when key and all modifier states match.\n\n```ts\nimport { matchStep, parseStep } from '@vielzeug/keymap/parse';\n\nconst step = parseStep('ctrl+k', 'ctrl')!;\nmatchStep(new KeyboardEvent('keydown', { ctrlKey: true, key: 'k' }), step); // true\n```\n\n---\n\n### `matchKey()`\n\n```ts\nfunction matchKey(event: KeyboardEvent, pattern: string, modKey?: 'ctrl' | 'meta'): boolean;\n```\n\nMatches a keyboard event against a single shortcut pattern such as `'ArrowDown'`, `'esc'`, `'mod+k'`, or `'shift+Home'`. Aliases and `mod` resolve through the same parser `createKeymap` uses, and modifier state must match exactly: `'ArrowDown'` does not match Ctrl+ArrowDown. Exported from both the root entry point and `@vielzeug/keymap/parse`.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | -------------------------------------------------------------------------------------------- |\n| `event` | `KeyboardEvent` | Event to match. Missing runtime `key` returns `false`. |\n| `pattern` | `string` | One shortcut step. Unparseable patterns and multi-step chords return `false` (never throws). |\n| `modKey` | `'ctrl' \\| 'meta'` | Optional. Resolution for `mod`; defaults to `detectModKey()`. |\n\n**Returns:** `true` only when key and all modifier states match.\n\n```ts\nimport { matchKey } from '@vielzeug/keymap';\n\nif (matchKey(event, 'mod+k')) openPalette();\nif (matchKey(event, 'shift+Home')) selectToStart(event);\n```\n\n---\n\n### `detectModKey()`\n\n```ts\nfunction detectModKey(): 'ctrl' | 'meta';\n```\n\nDetects Mac platform from `navigator` and otherwise returns `ctrl`.\n\n**Returns:** `'meta'` on Mac platforms; `'ctrl'` elsewhere or without `navigator`.\n\n```ts\nimport { detectModKey } from '@vielzeug/keymap/parse';\n\nconst modKey = detectModKey();\n```\n\n## Types\n\n### `Keymap`\n\nStateful shortcut manager returned by `createKeymap()`.\n\n```ts\ninterface Keymap {\n [Symbol.dispose](): void;\n bind(binding: Binding): () => void;\n dispose(): void;\n readonly disposalSignal: AbortSignal;\n readonly disposed: boolean;\n listBindings(): readonly BindingEntry[];\n mount(target: EventTarget): () => void;\n tap(handler: (event: KeymapEvent) => void, options?: { signal?: AbortSignal }): () => void;\n unbind(id: string): void;\n}\n```\n\n### `KeymapOptions`\n\nOptions applied to every binding owned by one manager.\n\n```ts\ninterface KeymapOptions {\n chordTimeout?: number;\n modKey?: 'ctrl' | 'meta';\n when?: When;\n}\n```\n\n- `when`: Guard function called for all bindings. When combined with per-binding `when` guards, both must return `true` for the handler to fire (AND composition). Global guard is checked first.\n- `chordTimeout`: Must be a positive finite number; `createKeymap()` throws `KeymapConfigError` otherwise. Defaults to `1000`.\n\n### `KeymapEvent`\n\nRuntime event observed through `tap()`.\n\n```ts\ntype KeymapEvent =\n | { type: 'chord-cancel'; target: EventTarget; trigger: 'keydown' | 'keyup' }\n | { type: 'chord-start'; step: ShortcutStep; target: EventTarget; trigger: 'keydown' | 'keyup' }\n | { type: 'chord-progress'; steps: readonly ShortcutStep[]; target: EventTarget; trigger: 'keydown' | 'keyup' }\n | { type: 'chord-timeout'; target: EventTarget; trigger: 'keydown' | 'keyup' }\n | { type: 'match'; binding: BindingEntry; target: EventTarget; trigger: 'keydown' | 'keyup' }\n | { type: 'dispose' };\n```\n\n`step`, `steps`, and `binding` are detached snapshots. Mutating them does not affect matching.\n\n### `Binding`\n\nPer-binding configuration. Each binding has an explicit `id` so duplicate shortcuts can coexist. Reusing an ID replaces its binding; among duplicate shortcuts, the first binding whose guard passes wins.\n\n```ts\ninterface Binding {\n id: string;\n shortcut: string;\n handler: Handler;\n trigger?: 'keydown' | 'keyup';\n when?: When;\n preventDefault?: boolean;\n stopPropagation?: boolean;\n}\n```\n\n- `trigger`: Defaults to `'keydown'`.\n- `preventDefault`: Defaults to `true`. Set to `false` for shortcuts that must retain browser behavior.\n- `stopPropagation`: Defaults to `false`.\n\n### `Handler` and `When`\n\n```ts\ntype Handler = (event: KeyboardEvent) => void;\ntype When = (event: KeyboardEvent) => boolean;\n```\n\n### `BindingEntry`\n\nDetached binding metadata returned by `listBindings()`.\n\n```ts\ntype BindingEntry = {\n readonly id: string;\n readonly shortcut: readonly ShortcutStep[];\n readonly trigger: 'keydown' | 'keyup';\n readonly preventDefault: boolean;\n readonly stopPropagation: boolean;\n};\n```\n\n### `ModifierKey`, `Shortcut`, and `ShortcutStep`\n\nParser types used by `parseShortcut()`, `parseStep()`, `matchStep()`, and `canonicalizeShortcut()`. Available from `@vielzeug/keymap/parse`.\n\n```ts\ntype ModifierKey = 'alt' | 'ctrl' | 'meta' | 'shift';\n\ntype ShortcutStep = {\n key: string;\n modifiers: Set<ModifierKey>;\n};\n\ntype Shortcut = ShortcutStep[];\n```\n\n### `ConflictOptions`\n\nComparison options for `findShortcutConflicts()`.\n\n```ts\ninterface ConflictOptions {\n modKey?: 'ctrl' | 'meta';\n trigger?: 'keydown' | 'keyup';\n}\n```\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| ------------------- | --------------------------------------------- | ------------------------------------------------------------------------------ |\n| `KeymapError` | Lifecycle operation after disposal | Use `instanceof KeymapError` to narrow Keymap errors. |\n| `KeymapConfigError` | `createKeymap()` receives an invalid option | Extends `KeymapError`. Thrown for a non-positive or non-finite `chordTimeout`. |\n| `KeymapParseError` | Strict shortcut parser receives invalid input | Extends `KeymapError`. |\n",
6
- "usage": "---\ntitle: 'Keymap: Usage Guide'\ndescription: Bind keyboard shortcuts, chords, event-aware guards, and target-local listeners with @vielzeug/keymap.\n---\n\n[[toc]]\n\n## Basic Usage\n\nMount one keymap, then release its target listener and dispose its owner during teardown.\n\n```ts\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst map = createKeymap([\n { id: 'save', shortcut: 'ctrl+s', handler: () => console.log('save') },\n { id: 'undo', shortcut: 'ctrl+z', handler: () => console.log('undo') },\n { id: 'close', shortcut: 'escape', handler: () => console.log('close') },\n]);\n\nconst unmount = map.mount(document);\n\n// Call this when the owning UI scope ends.\nunmount();\nmap.dispose();\n```\n\n`unmount()` only releases that target. `dispose()` releases every target, aborts `disposalSignal`, and makes `bind()`, `unbind()`, and `mount()` unavailable.\n\n## Modifier Aliases\n\nUse aliases to accept platform terminology while Keymap stores one canonical shortcut.\n\n| Input | Canonical modifier |\n| ----------------------- | ------------------------------- |\n| `cmd`, `command`, `win` | `meta` |\n| `opt`, `option` | `alt` |\n| `ctrl`, `control` | `ctrl` |\n| `mod` | `meta` on Mac; `ctrl` elsewhere |\n\nPass `modKey` when rendering or testing a specific platform.\n\n```ts\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst map = createKeymap([{ id: 'palette', shortcut: 'mod+k', handler: () => console.log('open palette') }], {\n modKey: 'ctrl',\n});\n\nmap.mount(document);\n```\n\n## Chord Sequences\n\nSeparate chord steps with spaces. Keymap resets an incomplete sequence after `chordTimeout` milliseconds.\n\n```ts\nconst map = createKeymap(\n [\n { id: 'save', shortcut: 'ctrl+k ctrl+s', handler: () => console.log('save') },\n { id: 'top', shortcut: 'g g', handler: () => window.scrollTo({ top: 0 }) },\n { id: 'end', shortcut: 'g e', handler: () => window.scrollTo({ top: document.body.scrollHeight }) },\n ],\n { chordTimeout: 800 },\n);\n```\n\nDo not bind a complete shortcut and a longer chord beginning with that shortcut. `g` fires immediately, so `g g` cannot complete. Check proposed user bindings with `findShortcutConflicts()`.\n\n## Binding Options\n\nEach binding is an object with an explicit `id`, `shortcut`, and `handler`. Add a guard, choose `keyup`, or control event behavior with optional fields.\n\n```ts\nconst map = createKeymap([\n { id: 'save', shortcut: 'ctrl+s', handler: () => saveDocument() },\n { id: 'close', shortcut: 'escape', handler: closePanel, when: (event) => event.target === panel },\n { id: 'play', shortcut: 'space', handler: togglePlayback, trigger: 'keyup' },\n { id: 'inspect', shortcut: 'f12', handler: inspectElement, preventDefault: false },\n]);\n```\n\n### Per-Binding preventDefault and stopPropagation\n\nEach binding controls `preventDefault` and `stopPropagation` independently:\n\n- `preventDefault` defaults to `true`: completed shortcuts and matched chord prefixes suppress browser defaults.\n- `stopPropagation` defaults to `false`: events continue bubbling unless explicitly stopped.\n\nSet `preventDefault: false` for shortcuts that must coexist with native controls (e.g. developer tools, accessibility features).\n\n## Context Guards\n\nUse global `when(event)` for policy shared by every binding. Use per-binding `when(event)` when one shortcut needs a narrower policy.\n\n```ts\nconst map = createKeymap(\n [\n { id: 'close', shortcut: 'escape', handler: closePanel, when: (event) => event.target === panel },\n { id: 'save', shortcut: 'ctrl+s', handler: () => saveDocument() },\n ],\n { when: (event) => !modalIsOpen() && event.isTrusted },\n);\n```\n\nAccept `KeyboardEvent` when guard logic needs target, modifier, composition, or shadow-DOM context.\n\n### Guard Composition: Global + Per-Binding\n\nWhen you provide both a global `when` (in `KeymapOptions`) and per-binding `when` guards, both must return `true` for the handler to fire. This is AND composition.\n\n**Guard evaluation and chord tracking order:**\n\n1. **Global guard runs first.** If it returns `false`, the target's pending chord state resets.\n2. **Per-binding guards select candidates.** A binding participates in each chord step only while its guard passes.\n3. **Chord state advances for eligible candidates.** The first completed candidate in binding order runs.\n\nA chord cannot begin while its map is disabled and finish after the global guard becomes active.\n\n```ts\nconst map = createKeymap(\n [\n { id: 'close', shortcut: 'escape', handler: closePanel, when: (event) => event.target === panel },\n { id: 'save', shortcut: 'ctrl+s', handler: () => saveDocument() },\n ],\n { when: (event) => !isModalOpen() && event.isTrusted },\n);\n\n// Global guard runs first; if false, both bindings are skipped (handler doesn't fire).\n// If global passes:\n// - 'save' handler fires immediately.\n// - 'close' handler fires only if event.target is the panel.\n```\n\n### Preserve Native Text Editing\n\nUse `event.composedPath()` to keep browser undo and redo inside inputs, textareas, and `contenteditable` elements. CRM app shell uses this policy for its global undo and redo shortcuts.\n\n```ts\nconst isTypingInField = (event: KeyboardEvent): boolean =>\n event\n .composedPath()\n .some(\n (target) =>\n target instanceof HTMLElement &&\n (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target.isContentEditable),\n );\n\nconst map = createKeymap(\n [\n { id: 'undo', shortcut: 'mod+z', handler: () => undo() },\n { id: 'redo', shortcut: 'mod+shift+z', handler: () => redo() },\n ],\n { when: (event) => !isTypingInField(event) },\n);\n```\n\nDo not make editable-field suppression a hidden package default. Applications may intentionally bind shortcuts inside editable controls.\n\n## Trigger Control\n\nBind on `keyup` when an action must run after key release.\n\n```ts\nconst map = createKeymap([{ id: 'confirm', shortcut: 'space', handler: confirmAction, trigger: 'keyup' }]);\n```\n\n`keydown` and `keyup` maintain independent chord state.\n\n## Replace Bindings at Runtime\n\n`bind(binding)` adds or replaces a binding with the same `id` and returns a targeted removal callback.\n\n```ts\nconst map = createKeymap([{ id: 'palette', shortcut: 'ctrl+k', handler: defaultAction }]);\nconst removePluginBinding = map.bind({ id: 'palette', shortcut: 'ctrl+k', handler: pluginAction });\n\nremovePluginBinding();\nmap.bind({ id: 'palette', shortcut: 'ctrl+k', handler: defaultAction });\n```\n\n`unbind(id)` removes the binding with that id and warns in development when no binding exists.\n\n### Duplicate Shortcuts with Different IDs\n\nEach binding has an explicit `id`, so duplicate shortcuts can coexist. Keymap evaluates them in insertion order and fires the first binding whose guard passes.\n\n```ts\nconst map = createKeymap([\n { id: 'primary', shortcut: 'ctrl+k', handler: primaryAction },\n { id: 'fallback', shortcut: 'ctrl+k', handler: fallbackAction },\n]);\n\n// 'primary' fires while eligible; use mutually exclusive guards for contextual fallback.\n```\n\n## Format Shortcut Labels\n\nFormat labels with explicit platform behavior when your UI is cross-platform.\n\n```ts\nimport { formatShortcut } from '@vielzeug/keymap';\n\nconsole.log(formatShortcut('mod+shift+p', 'meta')); // ⇧⌘P\nconsole.log(formatShortcut('mod+shift+p', 'ctrl')); // Ctrl+Shift+P\n```\n\n`formatShortcut()` returns `''` and emits a development warning for invalid input.\n\n## Detect Conflicts\n\nCheck a custom shortcut before binding it to prevent duplicate or unreachable chord paths.\n\n```ts\nimport { createKeymap, findShortcutConflicts } from '@vielzeug/keymap';\n\nconst map = createKeymap([{ id: 'top', shortcut: 'g', handler: () => scrollToTop() }]);\nconst conflicts = findShortcutConflicts('g g', map.listBindings());\n\nif (conflicts.length === 0) map.bind({ id: 'bottom', shortcut: 'g g', handler: () => scrollToBottom() });\n```\n\nConflict detection compares only bindings with same trigger. An empty proposal returns no conflicts; other invalid proposals throw `KeymapParseError`.\n\n## Parser Subpath\n\nFor custom tooling, validators, or framework integrations that need direct access to the shortcut parser, import from `@vielzeug/keymap/parse`:\n\n```ts\nimport { parseShortcut, parseStep, matchStep, canonicalizeShortcut } from '@vielzeug/keymap/parse';\n\nconst steps = parseShortcut('ctrl+k ctrl+s', 'ctrl');\nconst step = parseStep('ctrl+k', 'ctrl');\nconst isMatch = matchStep(new KeyboardEvent('keydown', { ctrlKey: true, key: 'k' }), steps[0]);\n```\n\n`matchKey()` and `detectModKey()` are also exported from the root entry point. For a one-off check against a pattern string, prefer `matchKey()`: it parses and matches in one call and returns `false` instead of throwing:\n\n```ts\nimport { matchKey } from '@vielzeug/keymap';\n\nif (matchKey(event, 'mod+k')) openPalette();\n```\n\n## Mount Targets\n\nMount one keymap on multiple independent targets when each target should own its own chord progression.\n\n```ts\nconst map = createKeymap([{ id: 'top', shortcut: 'g g', handler: () => console.log('go to top') }]);\nconst unmountEditor = map.mount(editor);\nconst unmountPreview = map.mount(preview);\n```\n\nA chord started on `editor` cannot complete on `preview`. Repeated `mount(editor)` calls share one listener and require one unmount call each. For nested targets, Keymap handles one bubbled event at its innermost mounted target.\n\n## Scoped Maps\n\nCreate separate keymaps for separate UI owners. If maps share a target and shortcut, guards must be mutually exclusive because Keymap has no implicit layer precedence.\n\n```ts\nconst baseMap = createKeymap([{ id: 'close-sidebar', shortcut: 'escape', handler: () => closeSidebar() }], {\n when: () => !modalIsOpen(),\n});\n\nconst modalMap = createKeymap([{ id: 'close-modal', shortcut: 'escape', handler: () => closeModal() }], {\n when: () => modalIsOpen(),\n});\n\nconst unmountBase = baseMap.mount(document);\nconst unmountModal = modalMap.mount(document);\n```\n\n## Observe Chord Activity\n\nUse `tap()` for chord hints, diagnostics, and matched-binding telemetry. Observers cannot alter shortcut behavior.\n\n```ts\nconst stopTrace = map.tap(\n (event) => {\n if (event.type === 'chord-start') showChordHint(event.step);\n if (event.type === 'chord-progress') updateChordHint(event.steps);\n if (event.type === 'chord-cancel' || event.type === 'chord-timeout' || event.type === 'match') hideChordHint();\n },\n { signal: owner.signal },\n);\n```\n\nTap handlers receive detached shortcut and binding snapshots. Handler errors are swallowed, and disposal emits a final `dispose` event before observers are cleared.\n\n## Testing\n\nDispatch `KeyboardEvent` instances against a mounted DOM target to test handlers and default prevention.\n\n```ts\nimport { expect, it, vi } from 'vitest';\n\nimport { createKeymap } from '@vielzeug/keymap';\n\nit('handles save', () => {\n const save = vi.fn();\n const target = document.createElement('button');\n const map = createKeymap([{ id: 'save', shortcut: 'ctrl+s', handler: save }]);\n const unmount = map.mount(target);\n\n target.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, ctrlKey: true, key: 's' }));\n\n expect(save).toHaveBeenCalledOnce();\n unmount();\n map.dispose();\n});\n```\n\nMount nested DOM targets in tests when your application uses both a container and a descendant listener. This verifies one bubbled event cannot complete a chord twice.\n\n## Framework Integration\n\nCreate map during framework lifecycle, then dispose it during teardown.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect } from 'react';\n\nimport { createKeymap } from '@vielzeug/keymap';\n\nexport function App() {\n useEffect(() => {\n const map = createKeymap([{ id: 'palette', shortcut: 'ctrl+k', handler: () => console.log('open palette') }]);\n const unmount = map.mount(document);\n\n return () => {\n unmount();\n map.dispose();\n };\n }, []);\n\n return null;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted } from 'vue';\n\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst map = createKeymap([{ id: 'close', shortcut: 'escape', handler: () => console.log('close palette') }]);\nlet unmount: (() => void) | undefined;\n\nonMounted(() => {\n unmount = map.mount(document);\n});\n\nonUnmounted(() => {\n unmount?.();\n map.dispose();\n});\n</script>\n```\n\n```ts [Svelte]\nimport { onMount } from 'svelte';\n\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst map = createKeymap([{ id: 'close', shortcut: 'escape', handler: () => console.log('close palette') }]);\n\nonMount(() => {\n const unmount = map.mount(document);\n\n return () => {\n unmount();\n map.dispose();\n };\n});\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### Keymap + Ledger\n\nConnect undo and redo handlers to a Ledger owner.\n\n```ts\nimport { createKeymap } from '@vielzeug/keymap';\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nconst reportHistoryError = (error: unknown): void => console.error(error);\nconst map = createKeymap([\n { id: 'undo', shortcut: 'mod+z', handler: () => void ledger.undo().catch(reportHistoryError) },\n { id: 'redo', shortcut: 'mod+shift+z', handler: () => void ledger.redo().catch(reportHistoryError) },\n]);\n\nmap.mount(document);\n```\n\n### Keymap + Herald\n\nEmit domain events instead of calling application actions from shortcut handlers.\n\n```ts\nimport { createBus } from '@vielzeug/herald';\nimport { createKeymap } from '@vielzeug/keymap';\n\nconst bus = createBus<{ 'shortcut:save': void }>();\nconst map = createKeymap([{ id: 'save', shortcut: 'ctrl+s', handler: () => bus.emit('shortcut:save') }]);\n\nmap.mount(document);\n```\n\n## Best Practices\n\n- **Dispose** every map when its owner ends.\n- **Unmount** temporary target listeners instead of disposing reusable maps.\n- **Guard** global text-editing shortcuts with `event.composedPath()`.\n- **Check** conflicts before accepting customized shortcuts.\n- **Keep** shared-target guards mutually exclusive.\n- **Use** `mod` for primary cross-platform shortcuts.\n- **Avoid** prefix pairs such as `g` and `g g`.\n- **Use** unique `id`s for each binding and mutually exclusive guards for intentional duplicate shortcuts.\n",
7
- "examples": "---\ntitle: 'Keymap: Examples'\ndescription: Worked examples for @vielzeug/keymap.\n---\n\n## Examples\n\n- [Global Shortcuts](./examples/global-shortcuts.md)\n- [Vim-style Navigation](./examples/vim-navigation.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "basic-shortcuts",
12
- "code": "import { createKeymap, formatShortcut } from '@vielzeug/keymap'\n\n// Create a keymap: each binding has an explicit id, shortcut, and handler.\n// Bindings fire on keydown by default; preventDefault defaults to true.\nconst map = createKeymap([\n { id: 'save', shortcut: 'ctrl+s', handler: () => console.log('save triggered') },\n { id: 'close', shortcut: 'escape', handler: () => console.log('close panel'), when: () => true },\n { id: 'play', shortcut: 'space', handler: () => console.log('toggle play'), trigger: 'keyup' },\n], { modKey: 'ctrl' })\n\n// Mount to document (required for event listening).\nconst unmount = map.mount(document)\n\n// Simulate events for demonstration.\ndocument.dispatchEvent(new KeyboardEvent('keydown', { key: 's', ctrlKey: true, bubbles: true }))\ndocument.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))\ndocument.dispatchEvent(new KeyboardEvent('keyup', { key: ' ', bubbles: true }))\n\n// Format shortcuts for display in UI tooltips or menus.\nconsole.log(formatShortcut('ctrl+s', 'ctrl')) // 'Ctrl+S'\nconsole.log(formatShortcut('mod+shift+p', 'meta')) // '⇧⌘P'\nconsole.log(formatShortcut('ctrl+k ctrl+s', 'ctrl')) // 'Ctrl+K Ctrl+S'\n\nunmount()",
13
- "name": "Basic Shortcuts"
14
- },
15
- {
16
- "id": "chord-sequences",
17
- "code": "import { createKeymap, findShortcutConflicts } from '@vielzeug/keymap'\n\n// Chord sequences fire only after all steps are pressed in order within the timeout.\n// Shortcut strings are lowercased before matching, so 'g g' and 'g G' are equivalent.\n// Different ids let both coexist, but the first eligible binding wins. Vim's actual 'G'\n// is shift+g, a single keystroke rather than a 'g'-prefixed chord.\nconst map = createKeymap([\n { id: 'save-all', shortcut: 'ctrl+k ctrl+s', handler: () => console.log('save all (VS Code-style)') },\n { id: 'top', shortcut: 'g g', handler: () => console.log('go to top (Vim-style)') },\n { id: 'bottom', shortcut: 'shift+g', handler: () => console.log('go to bottom') },\n], { chordTimeout: 800, modKey: 'ctrl' })\n\nconst unmount = map.mount(document)\n\n// Simulate completing 'ctrl+k ctrl+s' chord.\ndocument.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', ctrlKey: true, bubbles: true }))\ndocument.dispatchEvent(new KeyboardEvent('keydown', { key: 's', ctrlKey: true, bubbles: true }))\n\n// Simulate Vim 'g g' chord.\ndocument.dispatchEvent(new KeyboardEvent('keydown', { key: 'g', bubbles: true }))\ndocument.dispatchEvent(new KeyboardEvent('keydown', { key: 'g', bubbles: true }))\n\n// Gotcha: a single-key binding sharing a chord's first step always wins immediately,\n// making the longer chord unreachable: findShortcutConflicts() catches this up front.\nconsole.log('Would ctrl+k (alone) conflict with the chord above?')\nconsole.log(findShortcutConflicts('ctrl+k', map.listBindings()))\n\nunmount()",
18
- "name": "Chord Sequences"
19
- },
20
- {
21
- "id": "conflict-detection",
22
- "code": "import { createKeymap, findShortcutConflicts } from '@vielzeug/keymap'\n\n// findShortcutConflicts() catches unreachable bindings before you register them :\n// useful for a shortcut-customization UI driven by user input.\nconst map = createKeymap([\n { id: 'top', shortcut: 'g', handler: () => console.log('go to top') },\n])\n\nconst proposed = 'g g'\nconst conflicts = findShortcutConflicts(proposed, map.listBindings())\n\nif (conflicts.length > 0) {\n console.log(`\"${proposed}\" would never fire: shadowed by an existing binding`)\n} else {\n map.bind({ id: 'bottom', shortcut: proposed, handler: () => console.log('go to bottom') })\n}\n\n// A shortcut with no relationship to existing bindings reports no conflicts.\nconsole.log('ctrl+s conflicts:', findShortcutConflicts('ctrl+s', map.listBindings()).length)\n\n// keydown and keyup bindings never conflict: they're matched independently.\nconst withKeyup = createKeymap([\n { id: 'space-up', shortcut: 'space', handler: () => {}, trigger: 'keyup' },\n])\nconsole.log(\n 'space (keydown) vs space (keyup):',\n findShortcutConflicts('space', withKeyup.listBindings(), { trigger: 'keydown' }).length,\n)",
23
- "name": "Conflict Detection"
24
- },
25
- {
26
- "id": "format-and-conflicts",
27
- "code": "import { KeymapError, KeymapParseError, formatShortcut, findShortcutConflicts, createKeymap } from '@vielzeug/keymap'\n\n// formatShortcut turns a shortcut string into a display label.\nconst shortcuts = [\n ['mod+shift+p', 'meta'],\n ['mod+shift+p', 'ctrl'],\n ['ctrl+k ctrl+s', 'ctrl'],\n ['escape', 'ctrl'],\n ['space', 'meta'],\n]\n\nfor (const [shortcut, modKey] of shortcuts) {\n console.log(shortcut, '→', formatShortcut(shortcut, modKey))\n}\n\n// createKeymap() throws KeymapParseError for ambiguous or invalid steps.\n// Catch it with instanceof KeymapError to handle any keymap error.\ntry {\n createKeymap([{ id: 'bad', shortcut: 'ctrl+k+j', handler: () => {} }], { modKey: 'ctrl' })\n} catch (err) {\n console.log('Caught:', err instanceof KeymapError, err instanceof KeymapParseError, err.message)\n}\n\n// findShortcutConflicts() detects prefix/duplicate conflicts before binding.\nconst map = createKeymap([\n { id: 'top', shortcut: 'g', handler: () => console.log('go to top') },\n])\n\nconsole.log('Would \"g g\" conflict?', findShortcutConflicts('g g', map.listBindings()).length > 0)\nconsole.log('Would \"x\" conflict?', findShortcutConflicts('x', map.listBindings()).length > 0)",
28
- "name": "Format & Conflicts"
29
- },
30
- {
31
- "id": "shortcut-utilities",
32
- "code": "import { createKeymap, formatShortcut, findShortcutConflicts } from '@vielzeug/keymap'\n\n// listBindings(): inspect active bindings at runtime.\n// Each entry has id, shortcut (parsed steps), trigger, preventDefault, and stopPropagation.\nconst map = createKeymap(\n [\n { id: 'ctrl-k', shortcut: 'ctrl+k', handler: () => console.log('ctrl+k fired') },\n { id: 'save', shortcut: 'ctrl+shift+s', handler: () => console.log('save fired'), trigger: 'keyup' },\n { id: 'close', shortcut: 'escape', handler: () => console.log('close'), preventDefault: false },\n ],\n { modKey: 'ctrl' },\n)\n\nconst entries = map.listBindings()\nconsole.log('Bindings:', entries.length)\n\nfor (const entry of entries) {\n console.log(` ${entry.id}: trigger=${entry.trigger}, preventDefault=${entry.preventDefault}, stopPropagation=${entry.stopPropagation}`)\n}\n\n// formatShortcut(): display labels for UI tooltips or menus.\nconsole.log(formatShortcut('ctrl+k', 'ctrl')) // 'Ctrl+K'\nconsole.log(formatShortcut('mod+shift+p', 'meta')) // '⇧⌘P'\n\n// bind() returns an unbind closure: removes by binding id.\nconst unbind = map.bind({ id: 'ctrl-j', shortcut: 'ctrl+j', handler: () => console.log('ctrl+j') })\nconsole.log('After bind:', map.listBindings().length)\n\nunbind()\nconsole.log('After unbind:', map.listBindings().length)\n\n// unbind() removes by id, not by shortcut string: duplicate shortcuts coexist.\nmap.bind({ id: 'dup-a', shortcut: 'ctrl+d', handler: () => console.log('a') })\nmap.bind({ id: 'dup-b', shortcut: 'ctrl+d', handler: () => console.log('b') })\nconsole.log('Duplicate shortcut bindings:', map.listBindings().filter(e => e.shortcut.length === 1 && e.shortcut[0].key === 'd').length)\n\nmap.unbind('dup-a')\nconsole.log('After unbind dup-a:', map.listBindings().filter(e => e.shortcut.length === 1 && e.shortcut[0].key === 'd').length)\n\n// findShortcutConflicts(): check before binding a user-customized shortcut.\nconsole.log('ctrl+k conflicts:', findShortcutConflicts('ctrl+k', map.listBindings()).length)",
33
- "name": "Shortcut Utilities"
34
- }
35
- ],
36
- "typeSignatures": {
37
- "ConflictOptions": "export type { ConflictOptions } from './conflicts';",
38
- "findShortcutConflicts": "export { findShortcutConflicts } from './conflicts';",
39
- "KeymapConfigError": "export { KeymapConfigError, KeymapError, KeymapParseError } from './errors';",
40
- "KeymapError": "export { KeymapConfigError, KeymapError, KeymapParseError } from './errors';",
41
- "KeymapParseError": "export { KeymapConfigError, KeymapError, KeymapParseError } from './errors';",
42
- "formatShortcut": "export { formatShortcut, formatShortcutParts } from './format';",
43
- "formatShortcutParts": "export { formatShortcut, formatShortcutParts } from './format';",
44
- "createKeymap": "export { createKeymap } from './keymap';",
45
- "detectModKey": "export { detectModKey, matchKey } from './parser';",
46
- "matchKey": "export { detectModKey, matchKey } from './parser';",
47
- "Binding": "export type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';",
48
- "BindingEntry": "export type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';",
49
- "Handler": "export type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';",
50
- "Keymap": "export type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';",
51
- "KeymapEvent": "export type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';",
52
- "KeymapOptions": "export type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';",
53
- "When": "export type { Binding, BindingEntry, Handler, Keymap, KeymapEvent, KeymapOptions, When } from './types';"
54
- }
55
- }
@@ -1,60 +0,0 @@
1
- {
2
- "apiSource": "export { compose } from './compose';\nexport {\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerError,\n LedgerExecutionError,\n LedgerRollbackError,\n} from './errors';\nexport { createLedger } from './ledger';\nexport type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Ledger: Reversible async history'\ndescription: Serialized reversible command history with cancellation ownership and atomic reactive snapshots.\npackage: ledger\ncategory: utilities\nkeywords: [undo, redo, history, commands, async, reactive, ripple]\nexports:\n [\n compose,\n createLedger,\n LedgerError,\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerExecutionError,\n LedgerRollbackError,\n ]\nrelated: [ripple, keymap, forge, vault]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"ledger\" />\n\n## Why Ledger?\n\nUndo and redo require more than array manipulation when operations are asynchronous, cancellable, and visible in a UI. Ledger serializes only reversible commands, owns queue lifecycle, and publishes one atomic framework-neutral state snapshot without a reactive runtime dependency.\n\n```ts\n// Before\nconst undo = () => changes.pop()?.revert();\n\n// After\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nawait ledger.do({ apply: saveNext, revert: restorePrevious });\nawait ledger.undo();\n```\n\n| Feature | Roll your own | Ledger |\n| ----------------------- | ----------------------- | -------------------------------------------- |\n| Bundle size | 0 B | <PackageInfo package=\"ledger\" type=\"size\" /> |\n| Reversible history | Manual arrays | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Serialized async work | Manual queue | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Queue cancellation | Manual ownership | Abort-aware lifecycle |\n| Framework-neutral state | Manual events | Structural `Subscribable<LedgerState>` |\n| Composition | Custom transaction code | `compose()` |\n\n<div class=\"decision-callout\">\n\n**Use Ledger when** you own reversible asynchronous state transitions and need undo, redo, or history UI.\n\n**Consider direct application code when** work is irreversible, fire-and-forget, or does not need history.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/ledger\n```\n\n```sh [npm]\nnpm install @vielzeug/ledger\n```\n\n```sh [yarn]\nyarn add @vielzeug/ledger\n```\n\n:::\n\n## Quick Start\n\nSubmit a reversible command, read state, then dispose its owner.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nlet value = 'before';\nconst ledger = createLedger();\n\nawait ledger.do({\n apply: () => {\n value = 'after';\n },\n label: 'Rename value',\n revert: () => {\n value = 'before';\n },\n});\n\nawait ledger.undo();\nconsole.log(ledger.state.getSnapshot().undo.length); // 0\nledger.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createLedger()`: Create serialized reversible command history\n- `state`: Read atomic queue, undo, redo, and acceptance state\n- `compose()`: Combine reversible commands into one reversible command\n- `whenIdle()`: Await queued and active operation settlement\n- `LedgerCancelledError`: Distinguish cancellation from execution failure\n- `maxHistory`: Keep a non-negative safe-integer undo depth\n- `[Symbol.dispose]()`: Seal, abort, and clear a ledger owner\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ripple](/ripple/): Project Ledger's structural state readable into a signal when reactive derivations are needed.\n- [Keymap](/keymap/): Route undo and redo shortcuts to a Ledger error boundary.\n- [Forge](/forge/): Record reversible form transitions.\n- [Vault](/vault/): Persist application snapshots outside transient undo history.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Ledger: API Reference'\ndescription: Reference for serialized reversible commands, history state, composition, cancellation, disposal, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| -------------------------- | --------------------------------------- | ----------------- | ------------------------------------------- |\n| `createLedger()` | Create serialized reversible history | Sync construction | Every operation method is queued |\n| `compose()` | Combine commands into one history entry | Sync construction | Child metadata is not aggregated |\n| `ledger.do()` | Apply and record a command | Async | Failed or cancelled apply is not recorded |\n| `ledger.undo()` / `redo()` | Move the latest history entry | Async | Failures leave history on its original side |\n| `ledger.clear()` | Remove history without reverting | Async | Serialized behind earlier work |\n| `ledger.whenIdle()` | Await an empty operation queue | Async | Cannot force non-cooperative work to settle |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/ledger` | Complete Ledger runtime, error hierarchy, state-readable contract, unsubscribe type, and command/history types |\n\n## `createLedger()`\n\n```ts\nfunction createLedger<TMeta = undefined>(options?: LedgerOptions): Ledger<TMeta>;\n```\n\nCreates a ledger with one submission-order operation queue and one atomic state readable.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger<{ field: string }>({ maxHistory: 50 });\n```\n\n### `LedgerOptions`\n\n```ts\ninterface LedgerOptions {\n maxHistory?: number;\n}\n```\n\n`maxHistory` defaults to `100`. It must be a non-negative safe integer. `0` executes commands without retaining history.\n\n## `compose()`\n\n```ts\nfunction compose<TMeta = undefined>(\n commands: readonly ReversibleCommand<TMeta>[],\n label?: string,\n): ReversibleCommand<TMeta>;\n```\n\nSnapshots child command callbacks, applies children in order, and reverts them in reverse order. The result creates one history entry with the supplied label and `meta: undefined`.\n\nIf child application fails, completed children are compensated in reverse order. Compensation attempts continue after failures. Combined apply and compensation failures are preserved in an `AggregateError`, which Ledger exposes as `LedgerExecutionError.cause`. Normal composed reversion also attempts every child and reports failures through `LedgerRollbackError.cause` as an `AggregateError`.\n\n## `Ledger`\n\n```ts\ninterface Ledger<TMeta = undefined> {\n clear(): Promise<void>;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n do(command: ReversibleCommand<TMeta>, options?: LedgerCallOptions): Promise<void>;\n redo(options?: LedgerCallOptions): Promise<void>;\n readonly state: Subscribable<LedgerState<TMeta>>;\n undo(options?: LedgerCallOptions): Promise<void>;\n whenIdle(): Promise<void>;\n [Symbol.dispose](): void;\n}\n```\n\nAll operation methods are serialized in call order.\n\n### `do()`\n\nSnapshots the command's `apply`, `revert`, `label`, and metadata reference when submitted. On successful apply it appends one undo entry, evicts the oldest entry beyond `maxHistory`, and clears redo history. Apply failure rejects with `LedgerExecutionError` and records nothing. Ledger does not automatically revert a failed individual command.\n\n### `undo()`\n\nReverts the final undo entry. Success moves it to the end of redo history. If no undo entry exists, the queued operation resolves without changing history. Revert failure rejects with `LedgerRollbackError` and leaves the entry in undo history.\n\n### `redo()`\n\nApplies the final redo entry. Success moves it to the end of undo history. If no redo entry exists, it resolves without changing history. Apply failure rejects with `LedgerExecutionError` and leaves the entry in redo history.\n\n### `record()`\n\nAppends an already-executed command to undo history synchronously, without running it through the queue. For stores that execute their own writes: typically synchronous, embedded state stores: `undo()` calls the recorded `revert`, and `redo()` calls the recorded `apply`, so `apply` must be able to re-apply the effect. Recording shares `do()`'s bookkeeping: it clears redo history and evicts the oldest entry beyond `maxHistory`. It throws `LedgerDisposedError` on a disposed ledger.\n\n### `clear()`\n\nQueues removal of all undo and redo entries. It does not call command revert functions and does not cancel earlier work. When history is already empty it resolves without queueing; after disposal it rejects with `LedgerDisposedError`.\n\n### `whenIdle()`\n\nResolves immediately when `queued` and `running` are zero, otherwise resolves after both reach zero. Multiple waiters are supported. It rejects with `LedgerDisposedError` when the ledger is disposed, immediately or while waiting.\n\n### Disposal\n\n`dispose()` is permanent and idempotent. It clears undo and redo history, aborts active command contexts, rejects queued operations that have not started with `LedgerDisposedError`, and rejects pending `whenIdle()` waiters. Active commands must observe their signal and settle before `running` reaches zero. Read `disposed` to detect permanent disposal. `[Symbol.dispose]()` delegates to `dispose()`.\n\n## Command Types\n\n### `ReversibleCommand`\n\n```ts\ninterface ReversibleCommand<TMeta = undefined> {\n readonly apply: (context: CommandContext) => Promise<void> | void;\n readonly label?: string;\n readonly meta?: TMeta;\n readonly revert: (context: CommandContext) => Promise<void> | void;\n}\n```\n\n`apply` and `revert` may be synchronous or asynchronous. Metadata is retained by reference; Ledger does not deep-clone or deep-freeze it.\n\n### `CommandContext`\n\n```ts\ninterface CommandContext {\n readonly signal: AbortSignal;\n}\n```\n\nThe signal combines ledger disposal with the operation signal. Queued cancellation prevents user code from running. Active cancellation is cooperative. If user code ignores abort and completes, the operation still rejects with `LedgerCancelledError` and its history transition is not committed.\n\n### `LedgerCallOptions`\n\n```ts\ninterface LedgerCallOptions {\n signal?: AbortSignal;\n}\n```\n\nSupported by `do()`, `undo()`, and `redo()`. `clear()` has no call options.\n\n## State Types\n\n### `LedgerState`\n\n```ts\ninterface LedgerState<TMeta = undefined> {\n readonly queued: number;\n readonly redo: readonly HistoryEntry<TMeta>[];\n readonly running: number;\n readonly undo: readonly HistoryEntry<TMeta>[];\n}\n```\n\n| Field | Meaning |\n| --------- | ----------------------------------------------------------------------- |\n| `queued` | Submitted operations that have not started |\n| `running` | Currently executing operation; serialization keeps this at 0 or 1 |\n| `undo` | Chronological successfully applied history; final entry is next to undo |\n| `redo` | Chronological reverted history; final entry is next to redo |\n\nState objects and history arrays are frozen replacements.\n\n### `HistoryEntry`\n\n```ts\ninterface HistoryEntry<TMeta = undefined> {\n readonly label: string | undefined;\n readonly meta: TMeta | undefined;\n}\n```\n\nHistory entries are frozen and intentionally omit command callbacks.\n\n### `Subscribable` and `Unsubscribe`\n\n`Ledger.state` implements this framework-neutral structural contract, which matches `Subscribable` in `@vielzeug/arsenal`. Both names are root type exports.\n\n```ts\ntype Unsubscribe = () => void;\n\ninterface Subscribable<T> {\n getSnapshot(): T;\n subscribe(listener: () => void): Unsubscribe;\n}\n```\n\nSubscriptions are not immediate and receive no value argument. Listeners run synchronously from a snapshot after state replacement. A listener failure does not interrupt Ledger bookkeeping or later listeners; it is rethrown in a microtask.\n\n## Errors\n\n| Error | Trigger | History result |\n| ---------------------- | ------------------------------------------------------------- | ------------------------------------------ |\n| `LedgerCancelledError` | Queued signal cancellation or active cooperative cancellation | No transition committed |\n| `LedgerDisposedError` | Submission after disposal or queued work rejected by disposal | History already cleared by disposal |\n| `LedgerExecutionError` | `apply()` fails during `do()` or `redo()` | New command absent, or redo entry retained |\n| `LedgerRollbackError` | `revert()` fails during `undo()` | Undo entry retained |\n| `LedgerConfigError` | Invalid `maxHistory` | Construction fails |\n| `LedgerError` | Base class and internal history corruption | Depends on operation |\n\nWrapped operation failures preserve the original value in `.cause`. Use `instanceof LedgerError` to catch the hierarchy, then narrow to a specific subtype.\n",
6
- "usage": "---\ntitle: 'Ledger: Usage Guide'\ndescription: Record reversible commands, observe serialized history, handle failures, and own cancellation and disposal.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCapture both sides of a reversible transition before submitting it.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nusing ledger = createLedger();\nconst item = { name: 'Old name' };\nconst previous = item.name;\nconst next = 'New name';\n\nawait ledger.do({\n apply: () => {\n item.name = next;\n },\n label: 'Rename item',\n revert: () => {\n item.name = previous;\n },\n});\n\nawait ledger.undo();\nawait ledger.redo();\n```\n\nAll `do()`, `undo()`, `redo()`, and `clear()` calls join one submission-order queue. Keep irreversible effects outside commands unless they have a real compensating operation.\n\n## Read Atomic State\n\n`state` is a framework-neutral `Subscribable`, not a Ripple signal. Read `getSnapshot()`, and subscribe to invalidation callbacks.\n\n```ts\nfunction renderHistory(): void {\n const { queued, redo, running, undo } = ledger.state.getSnapshot();\n undoButton.disabled = undo.length === 0 || ledger.disposed;\n redoButton.disabled = redo.length === 0 || ledger.disposed;\n spinner.hidden = queued + running === 0;\n}\n\nrenderHistory();\nconst stop = ledger.state.subscribe(renderHistory);\n```\n\nSubscriptions are not immediate and receive no value argument. They run synchronously from a listener snapshot after every state replacement. A failure is rethrown in a microtask without interrupting Ledger bookkeeping or later subscribers.\n\nState objects, history arrays, and history entries are frozen snapshots. `undo` and `redo` are chronological; the next command to undo or redo is the final item. Metadata values are retained by reference rather than deep-cloned.\n\n## Attach History Metadata\n\nSet `label` for presentation and use the ledger's metadata type for application context.\n\n```ts\nconst ledger = createLedger<{ field: string }>();\n\nawait ledger.do({\n apply: () => {\n form.email = next;\n },\n label: 'Edit email',\n meta: { field: 'email' },\n revert: () => {\n form.email = previous;\n },\n});\n\nconsole.log(ledger.state.getSnapshot().undo.at(-1));\n```\n\nLedger snapshots command callbacks, label, and metadata references when `do()` is submitted. Later mutation of the command object does not replace the captured callbacks.\n\n## Compose Reversible Commands\n\n`compose()` produces one command and one history entry. Children apply in order and revert in reverse order.\n\n```ts\nimport { compose } from '@vielzeug/ledger';\n\nawait ledger.do(\n compose(\n [\n {\n apply: () => {\n node.x = nextX;\n },\n revert: () => {\n node.x = previousX;\n },\n },\n {\n apply: () => {\n node.y = nextY;\n },\n revert: () => {\n node.y = previousY;\n },\n },\n ],\n 'Move node',\n ),\n);\n```\n\nIf a child apply fails, already-applied children are compensated in reverse order. Compensation continues after failures. If application and compensation both fail, `LedgerExecutionError.cause` is an `AggregateError` containing all failures. A composed command records the supplied label but does not aggregate child metadata.\n\n## Handle Operation Failures\n\n```ts\nimport { LedgerCancelledError, LedgerExecutionError, LedgerRollbackError } from '@vielzeug/ledger';\n\ntry {\n await ledger.undo();\n} catch (error) {\n if (error instanceof LedgerCancelledError) {\n // Expected cancellation.\n } else if (error instanceof LedgerRollbackError) {\n showUndoError(error.cause);\n } else if (error instanceof LedgerExecutionError) {\n showApplyError(error.cause);\n } else {\n throw error;\n }\n}\n```\n\nA failed `do()` is not recorded and is not automatically reverted. A failed `undo()` remains in undo history; a failed `redo()` remains in redo history, allowing retry after the underlying problem is corrected.\n\n## Cancel Work\n\nPass a signal per operation. Queued cancellation prevents user code from starting. Active work receives a combined signal and must stop cooperatively.\n\n```ts\nconst controller = new AbortController();\nconst operation = ledger.do(\n {\n apply: ({ signal }) => saveDraft(nextDraft, { signal }),\n revert: ({ signal }) => saveDraft(previousDraft, { signal }),\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\nawait operation.catch(handleHistoryFailure);\n```\n\nIf active user code ignores cancellation and finishes, Ledger rejects with `LedgerCancelledError` and does not record or move history. It does not compensate partial effects automatically, so command implementations must check or forward `context.signal` before committing changes.\n\n## Record Externally Executed Work\n\nWhen a synchronous store owns its writes, execute first and record the reversible entry afterwards: `undo()` calls the recorded `revert`, `redo()` calls the recorded `apply`, so `apply` must be able to re-apply the effect.\n\n```ts\nconst previous = item.name;\n\nitem.name = next; // the store's own synchronous write\nledger.record({\n apply: () => {\n item.name = next;\n },\n label: 'rename item',\n revert: () => {\n item.name = previous;\n },\n});\n```\n\nRecording is synchronous and shares `do()`'s bookkeeping: it clears redo history and evicts the oldest entry beyond `maxHistory`.\n\n## Limit and Clear History\n\n`maxHistory` defaults to `100` and accepts non-negative safe integers. Successful commands beyond the cap evict the oldest undo entries. `0` executes commands without retaining undo or redo history.\n\n```ts\nconst ledger = createLedger({ maxHistory: 30 });\nawait ledger.clear();\n```\n\n`clear()` is serialized behind earlier work and clears both history arrays without reverting commands.\n\n## Drain and Dispose\n\n`whenIdle()` resolves when both `queued` and `running` reach zero. It does not cancel work.\n\n```ts\nconst operation = ledger.do(command);\nconst idle = ledger.whenIdle();\n\nledger.dispose();\nawait operation.catch(handleHistoryFailure);\nawait idle;\n```\n\nDisposal is permanent and idempotent. It clears history, aborts active contexts, rejects queued work with `LedgerDisposedError`, and rejects pending `whenIdle()` waiters. Read `disposed` to detect it. Active operations settle cooperatively; `whenIdle()` waits for them. Work that never settles can keep `whenIdle()` pending.\n\n## Framework Integration\n\nKeep one ledger per owning scope and adapt its structural readable through the framework's subscription API.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport { createLedger } from '@vielzeug/ledger';\n\nexport function UndoStatus() {\n const ledger = useMemo(() => createLedger(), []);\n const state = useSyncExternalStore(\n (notify) => ledger.state.subscribe(notify),\n () => ledger.state.getSnapshot(),\n () => ledger.state.getSnapshot(),\n );\n\n useEffect(() => () => ledger.dispose(), [ledger]);\n return (\n <span>\n {state.undo.length} undo / {state.redo.length} redo\n </span>\n );\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nconst state = shallowRef(ledger.state.getSnapshot());\nconst stop = ledger.state.subscribe(() => {\n state.value = ledger.state.getSnapshot();\n});\n\nonUnmounted(() => {\n stop();\n ledger.dispose();\n});\n```\n\n```ts [Ripple]\nimport { signal } from '@vielzeug/ripple';\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nconst state = signal(ledger.state.getSnapshot());\nconst stop = ledger.state.subscribe(() => {\n state.value = ledger.state.getSnapshot();\n});\n\nfunction dispose(): void {\n stop();\n ledger.dispose();\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse Keymap to route keyboard shortcuts into `undo()` and `redo()`. Project `ledger.state` into Ripple when reactive derivations are needed. Persist application snapshots with Vault; Ledger history itself is transient.\n\n## Best Practices\n\n- Capture previous and next values before submitting a command.\n- Keep irreversible effects outside Ledger commands.\n- Forward or check `context.signal` in asynchronous command work.\n- Catch every operation promise at the application boundary.\n- Read one `state` snapshot per render.\n- Keep state subscribers synchronous and handle failures through the application's global error boundary.\n- Use `whenIdle()` before releasing owners that require a drain boundary.\n- Dispose each owner-scoped ledger.\n",
7
- "examples": "---\ntitle: 'Ledger: Examples'\ndescription: Recipes for reversible editor and form history with Ledger.\n---\n\n## Examples\n\n- [Text Editor History](./examples/text-editor.md)\n- [JSON Delta History](./examples/json-delta-history.md)\n- [Form History](./examples/form-history.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "cancellation",
12
- "code": "import { LedgerCancelledError, createLedger } from '@vielzeug/ledger'\n\nconst ledger = createLedger()\nconst controller = new AbortController()\n\nconst save = ledger.do(\n {\n apply: async ({ signal }) => {\n if (signal.aborted) throw new Error('save aborted')\n await new Promise((resolve) => setTimeout(resolve, 50))\n },\n revert: () => {},\n },\n { signal: controller.signal },\n)\n\ncontroller.abort()\n\ntry {\n await save\n} catch (error) {\n console.log('cancelled:', error instanceof LedgerCancelledError)\n}\n\nconsole.log('undo entries:', ledger.state.getSnapshot().undo.length)\nledger.dispose()",
13
- "name": "Cancellation"
14
- },
15
- {
16
- "id": "command-data",
17
- "code": "import { createLedger } from '@vielzeug/ledger'\n\nconst ledger = createLedger()\nconst documentState = { title: 'Untitled' }\nconst previous = documentState.title\n\nawait ledger.do({\n apply: () => { documentState.title = 'Hello World' },\n label: 'Set title',\n meta: { after: 'Hello World', before: previous, field: 'title' },\n revert: () => { documentState.title = previous },\n})\n\nconsole.log('state:', documentState)\nconsole.log('history meta:', ledger.state.getSnapshot().undo.at(-1)?.meta)\nconsole.log('queued:', ledger.state.getSnapshot().queued)\nconsole.log('running:', ledger.state.getSnapshot().running)\n\nawait ledger.undo()\nconsole.log('after undo:', documentState)\nledger.dispose()",
18
- "name": "History Metadata & State"
19
- },
20
- {
21
- "id": "compose-commands",
22
- "code": "import { compose, createLedger } from '@vielzeug/ledger'\n\nconst ledger = createLedger()\nconst node = { x: 0, y: 0 }\n\nawait ledger.do(compose([\n {\n apply: () => { node.x = 100 },\n revert: () => { node.x = 0 },\n },\n {\n apply: () => { node.y = 50 },\n revert: () => { node.y = 0 },\n },\n], 'Move node'))\n\nconsole.log('after apply:', node)\nconsole.log('undo entries:', ledger.state.getSnapshot().undo.length)\n\nawait ledger.undo()\nconsole.log('after revert:', node)\nledger.dispose()",
23
- "name": "Compose Reversible Commands"
24
- },
25
- {
26
- "id": "do-undo-redo",
27
- "code": "import { createLedger } from '@vielzeug/ledger'\n\nconst ledger = createLedger()\nlet counter = 0\n\nasync function increment() {\n const previous = counter\n const next = previous + 1\n\n await ledger.do({\n apply: () => { counter = next },\n label: 'Increment',\n revert: () => { counter = previous },\n })\n}\n\nawait increment()\nawait increment()\nawait increment()\nconsole.log('after increments:', counter)\nconsole.log('undo entries:', ledger.state.getSnapshot().undo.length)\n\nawait ledger.undo()\nconsole.log('after undo:', counter)\n\nawait ledger.redo()\nconsole.log('after redo:', counter)\nledger.dispose()",
28
- "name": "do / undo / redo"
29
- },
30
- {
31
- "id": "reactive-signals",
32
- "code": "import { createLedger } from '@vielzeug/ledger'\n\nconst ledger = createLedger({ maxHistory: 5 })\nconst snapshots = []\nconst stop = ledger.state.subscribe(() => {\n snapshots.push(ledger.state.getSnapshot())\n})\nlet value = 0\n\nfor (const label of ['Increase', 'Increase again']) {\n const previous = value\n await ledger.do({\n apply: () => { value += 1 },\n label,\n revert: () => { value = previous },\n })\n}\n\nconsole.log('undo labels:', ledger.state.getSnapshot().undo.map(entry => entry.label))\nconsole.log('queued/running:', ledger.state.getSnapshot().queued, ledger.state.getSnapshot().running)\n\nawait ledger.clear()\nconsole.log('undo entries after clear:', ledger.state.getSnapshot().undo.length)\nconsole.log('state replacements:', snapshots.length)\nstop()\nledger.dispose()",
33
- "name": "Structural State Subscription"
34
- },
35
- {
36
- "id": "rollback-error",
37
- "code": "import { LedgerRollbackError, createLedger } from '@vielzeug/ledger'\n\nconst ledger = createLedger()\n\nawait ledger.do({\n apply: () => console.log('applied'),\n label: 'Update draft',\n revert: () => { throw new Error('draft is locked') },\n})\n\ntry {\n await ledger.undo()\n} catch (error) {\n if (error instanceof LedgerRollbackError) {\n console.log('revert failed:', error.message)\n }\n}\n\nconsole.log('undo entries:', ledger.state.getSnapshot().undo.length)\nledger.dispose()",
38
- "name": "Rollback Error"
39
- }
40
- ],
41
- "typeSignatures": {
42
- "compose": "export { compose } from './compose';",
43
- "LedgerCancelledError": "export {\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerError,\n LedgerExecutionError,\n LedgerRollbackError,\n} from './errors';",
44
- "LedgerConfigError": "export {\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerError,\n LedgerExecutionError,\n LedgerRollbackError,\n} from './errors';",
45
- "LedgerDisposedError": "export {\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerError,\n LedgerExecutionError,\n LedgerRollbackError,\n} from './errors';",
46
- "LedgerError": "export {\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerError,\n LedgerExecutionError,\n LedgerRollbackError,\n} from './errors';",
47
- "LedgerExecutionError": "export {\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerError,\n LedgerExecutionError,\n LedgerRollbackError,\n} from './errors';",
48
- "LedgerRollbackError": "export {\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerError,\n LedgerExecutionError,\n LedgerRollbackError,\n} from './errors';",
49
- "createLedger": "export { createLedger } from './ledger';",
50
- "CommandContext": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
51
- "HistoryEntry": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
52
- "Ledger": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
53
- "LedgerCallOptions": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
54
- "LedgerOptions": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
55
- "LedgerState": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
56
- "ReversibleCommand": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
57
- "Subscribable": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';",
58
- "Unsubscribe": "export type {\n CommandContext,\n HistoryEntry,\n Ledger,\n LedgerCallOptions,\n LedgerOptions,\n LedgerState,\n ReversibleCommand,\n Subscribable,\n Unsubscribe,\n} from './types';"
59
- }
60
- }