@kerf-js/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +554 -2
  3. package/bin/kerf.mjs +15 -0
  4. package/docs/async.md +50 -0
  5. package/docs/browser.md +53 -0
  6. package/docs/config.md +127 -0
  7. package/docs/core.md +30 -0
  8. package/docs/deploy.md +108 -0
  9. package/docs/design.md +106 -0
  10. package/docs/entrypoints.md +83 -0
  11. package/docs/fonts.md +118 -0
  12. package/docs/icons.md +108 -0
  13. package/docs/lists.md +25 -0
  14. package/docs/meta.md +92 -0
  15. package/docs/plugins.md +166 -0
  16. package/docs/props.md +88 -0
  17. package/docs/reactivity.md +26 -0
  18. package/docs/rules.md +39 -0
  19. package/docs/rust.md +253 -0
  20. package/docs/start-short.md +10 -0
  21. package/docs/start.md +642 -0
  22. package/docs/state.md +122 -0
  23. package/docs/style.md +82 -0
  24. package/docs/surface.md +158 -0
  25. package/docs/testing.md +81 -0
  26. package/docs/theme.md +263 -0
  27. package/docs/ui-state.md +105 -0
  28. package/docs/verify.md +61 -0
  29. package/package.json +47 -3
  30. package/src/add/config.mjs +93 -0
  31. package/src/add/errors.mjs +2 -0
  32. package/src/add/setup.mjs +88 -0
  33. package/src/add-rust.mjs +178 -0
  34. package/src/add.mjs +392 -0
  35. package/src/agents-md.mjs +240 -0
  36. package/src/alias.mjs +70 -0
  37. package/src/audit/page.mjs +313 -0
  38. package/src/audit/report.mjs +69 -0
  39. package/src/audit/utils.mjs +5 -0
  40. package/src/audit.mjs +319 -0
  41. package/src/browser/cli.mjs +53 -0
  42. package/src/browser/client.mjs +299 -0
  43. package/src/browser/commands.mjs +258 -0
  44. package/src/capture.mjs +21 -0
  45. package/src/catalog/audit.mjs +129 -0
  46. package/src/catalog/auth.mjs +40 -0
  47. package/src/catalog/compiler.mjs +337 -0
  48. package/src/catalog/contracts.mjs +18 -0
  49. package/src/catalog/database.mjs +52 -0
  50. package/src/catalog/deploy.mjs +117 -0
  51. package/src/catalog/design.mjs +159 -0
  52. package/src/catalog/forms.mjs +25 -0
  53. package/src/catalog/hydration.mjs +29 -0
  54. package/src/catalog/icons.mjs +24 -0
  55. package/src/catalog/media.mjs +163 -0
  56. package/src/catalog/metadata.mjs +116 -0
  57. package/src/catalog/plugins.mjs +228 -0
  58. package/src/catalog/realtime.mjs +195 -0
  59. package/src/catalog/rust.mjs +75 -0
  60. package/src/catalog/server-functions.mjs +100 -0
  61. package/src/catalog/state.mjs +39 -0
  62. package/src/catalog/style-groups.mjs +54 -0
  63. package/src/catalog/tests.mjs +127 -0
  64. package/src/catalog/text.mjs +200 -0
  65. package/src/catalog/ui-state.mjs +42 -0
  66. package/src/catalog.mjs +103 -0
  67. package/src/check/runtime.mjs +280 -0
  68. package/src/check.mjs +321 -0
  69. package/src/cli/authoring.mjs +213 -0
  70. package/src/cli/project.mjs +302 -0
  71. package/src/cli.mjs +340 -0
  72. package/src/config.d.ts +1 -0
  73. package/src/config.mjs +5 -0
  74. package/src/contributions.mjs +119 -0
  75. package/src/db-layer.mjs +41 -0
  76. package/src/deploy/cdn.mjs +142 -0
  77. package/src/deploy/files.mjs +266 -0
  78. package/src/deploy/fit.mjs +166 -0
  79. package/src/deploy/hosts.mjs +126 -0
  80. package/src/deploy/index/cli.mjs +20 -0
  81. package/src/deploy/index/environment.mjs +69 -0
  82. package/src/deploy/index/steps.mjs +87 -0
  83. package/src/deploy/index.mjs +387 -0
  84. package/src/deploy/needs.mjs +149 -0
  85. package/src/design-checks/accessible-names.mjs +62 -0
  86. package/src/design-checks/contrast.mjs +43 -0
  87. package/src/design-checks/csp.mjs +60 -0
  88. package/src/design-checks/files.mjs +59 -0
  89. package/src/design-checks/heading-links.mjs +61 -0
  90. package/src/design-checks/interaction.mjs +65 -0
  91. package/src/design-checks/jsx.mjs +67 -0
  92. package/src/design-checks/layout-values.mjs +68 -0
  93. package/src/design-checks/native-controls.mjs +48 -0
  94. package/src/design-checks/outline.mjs +39 -0
  95. package/src/design-checks/reporter.mjs +37 -0
  96. package/src/design-checks/rules.mjs +274 -0
  97. package/src/design-checks/values.mjs +262 -0
  98. package/src/design-checks.mjs +49 -0
  99. package/src/diag.mjs +98 -0
  100. package/src/docs.mjs +228 -0
  101. package/src/doctor.mjs +42 -0
  102. package/src/files.mjs +60 -0
  103. package/src/fix.mjs +48 -0
  104. package/src/gate/after.mjs +40 -0
  105. package/src/gate/before.mjs +54 -0
  106. package/src/gate/classify.mjs +72 -0
  107. package/src/gate/mutation.mjs +209 -0
  108. package/src/gate/resolve-cases.mjs +22 -0
  109. package/src/gate/result.mjs +63 -0
  110. package/src/gate/run.mjs +75 -0
  111. package/src/gate.mjs +178 -0
  112. package/src/index.mjs +9 -0
  113. package/src/infer/box-props.cjs +140 -0
  114. package/src/infer/core-boxes.cjs +46 -0
  115. package/src/infer/derived-writes.cjs +95 -0
  116. package/src/infer/engine/checks.cjs +193 -0
  117. package/src/infer/engine/flow.cjs +293 -0
  118. package/src/infer/engine/report.cjs +158 -0
  119. package/src/infer/engine/utils.cjs +15 -0
  120. package/src/infer/engine.cjs +265 -0
  121. package/src/infer/facts/sites.cjs +114 -0
  122. package/src/infer/facts.cjs +345 -0
  123. package/src/infer/hosts.cjs +161 -0
  124. package/src/infer/lsp.mjs +240 -0
  125. package/src/infer/session.cjs +161 -0
  126. package/src/infer/shadow.cjs +54 -0
  127. package/src/infer/worker.cjs +145 -0
  128. package/src/jsx-scan.mjs +128 -0
  129. package/src/kerf.mjs +98 -0
  130. package/src/load-config/schema.mjs +300 -0
  131. package/src/load-config.mjs +302 -0
  132. package/src/map.mjs +177 -0
  133. package/src/mcp/browser-tools.mjs +155 -0
  134. package/src/mcp.mjs +273 -0
  135. package/src/meta-table.mjs +63 -0
  136. package/src/mutate.mjs +224 -0
  137. package/src/plugin-checks.mjs +118 -0
  138. package/src/plugins.mjs +258 -0
  139. package/src/project.mjs +310 -0
  140. package/src/props-checks.mjs +64 -0
  141. package/src/props-listener.mjs +56 -0
  142. package/src/react-checks.mjs +67 -0
  143. package/src/server-state-checks.mjs +34 -0
  144. package/src/share-checks.mjs +158 -0
  145. package/src/site.mjs +46 -0
  146. package/src/slots.mjs +181 -0
  147. package/src/start/build.mjs +116 -0
  148. package/src/start/routes.mjs +38 -0
  149. package/src/start.mjs +394 -0
  150. package/src/state-checks/core-state.mjs +223 -0
  151. package/src/state-checks/modules.mjs +17 -0
  152. package/src/state-checks/scan.mjs +232 -0
  153. package/src/state-checks/server-graph.mjs +65 -0
  154. package/src/state-checks.mjs +189 -0
  155. package/src/style/find.mjs +121 -0
  156. package/src/style.mjs +327 -0
  157. package/src/surface-checks.mjs +384 -0
  158. package/src/tailwind.mjs +23 -0
  159. package/src/tasks.mjs +261 -0
  160. package/src/test-rules/context.mjs +109 -0
  161. package/src/test-rules/file-rules.mjs +279 -0
  162. package/src/test-rules/rule-helpers.mjs +244 -0
  163. package/src/test-rules/syntax.mjs +223 -0
  164. package/src/test-rules/test-rules.mjs +127 -0
  165. package/src/testdiff.mjs +219 -0
  166. package/src/tests.mjs +120 -0
  167. package/src/text-checks.mjs +332 -0
  168. package/src/tokens.mjs +33 -0
  169. package/src/trust/scan.mjs +95 -0
  170. package/src/trust.mjs +394 -0
  171. package/src/workspace.mjs +182 -0
  172. package/ts-plugin/context.js +57 -0
  173. package/ts-plugin/index.js +17 -0
  174. package/ts-plugin/mapping.js +65 -0
  175. package/ts-plugin/package.json +1 -0
  176. package/ts-plugin/proxy.js +144 -0
package/docs/state.md ADDED
@@ -0,0 +1,122 @@
1
+ # State (`@kerf-js/core`)
2
+
3
+ Every reactive function in one place. The rules for using them are `kerf docs rules`; props are `kerf docs props`.
4
+
5
+ ```tsx
6
+ import {
7
+ derived,
8
+ flush,
9
+ onCleanup,
10
+ onMount,
11
+ state,
12
+ watch,
13
+ } from '@kerf-js/core'
14
+
15
+ export function Counter() {
16
+ const count = state(0)
17
+ const label = derived(() => `Clicked ${count.value} times`)
18
+ let input: HTMLInputElement | undefined
19
+
20
+ watch(() => label.value, text => {
21
+ document.title = text
22
+ return () => (document.title = 'App')
23
+ })
24
+ onMount(() => input?.focus())
25
+ onCleanup(() => console.log('Counter removed'))
26
+
27
+ const reset = () => {
28
+ count.value = 0
29
+ flush() // the DOM shows 0 now, before the focus below
30
+ input?.select()
31
+ }
32
+ return (
33
+ <p>
34
+ <button type="button" onClick={() => count.value++}>
35
+ {label.value}
36
+ </button>
37
+ <input
38
+ ref={(n: HTMLInputElement) => (input = n)}
39
+ aria-label="Note"
40
+ />
41
+ <button type="button" onClick={reset}>Reset</button>
42
+ </p>
43
+ )
44
+ }
45
+ ```
46
+
47
+ ## Boxes and derived values
48
+
49
+ | Call | Gives |
50
+ |---|---|
51
+ | `state(init, options?)` | A box: read and write `.value`. A write that is `Object.is` the old value does nothing |
52
+ | `box.set(d => { d.x = 1 })` | Updates a copy: arrays and objects are copied one level, then written as a new value |
53
+ | `box.get(key)` | One entry of an object box. The reader re-runs only when that entry changes (W017) |
54
+ | `state.linked(() => source, { key? })` | A box that follows `source` until written. With `key`, an edit holds while the key stays, and `.conflict.value` says when the source moved under it |
55
+ | `derived(() => …)` | A read-only value, computed when read and cached until what it read changes |
56
+
57
+ `get`, `set` and `state.linked` come from `@kerf-js/core/keyed`. The main entry and the kerf() Vite plugin bring it in
58
+ when a module uses them, so you only import it yourself when the name is built at run time (`box[name]`).
59
+
60
+ Writes are batched: effects and DOM updates run together on the next microtask. `flush()` runs them now, for example
61
+ before `focus()` on an element a write just showed. `batch(fn)` runs `fn` and exists only to say this at the call.
62
+
63
+ ## Effects and owners
64
+
65
+ - `watch(() => source, (value, prev) => cleanup?)`: runs `act` now and whenever `source` changes. Only `source` is
66
+ tracked. A returned function runs before the next run and when the owner goes.
67
+ - `onMount(fn)`: runs once the component's DOM is in place and refs are set. Never on the server.
68
+ - `onCleanup(fn)`: runs when the owner (a component, a `createRoot`, a list row) is disposed.
69
+ - `untrack(() => …)`: reads without subscribing. The result never updates (W018 if only JSX reads it).
70
+ - `createRoot(dispose => …)`: an owner that outlives its caller, ended by `dispose()`.
71
+ - `context(fallback)`: `ctx.provide(value, () => …)` sets a value for everything created inside; `ctx.use` reads the
72
+ nearest one.
73
+
74
+ ## Shared state: `defineState`
75
+
76
+ A named scope of state that any component can import. Its setup runs once per app, the first time it's used, and
77
+ returns boxes, derived values and actions. Each action call is one transaction and one undo step.
78
+
79
+ ```ts
80
+ import { defineState, derived, state } from '@kerf-js/core'
81
+ import { z } from 'zod'
82
+
83
+ export const cart = defineState('cart', () => {
84
+ const lines = state<Record<string, number>>({}, {
85
+ persist: {
86
+ in: 'local',
87
+ schema: z.record(z.string(), z.number()),
88
+ version: 1,
89
+ },
90
+ sync: 'tabs',
91
+ })
92
+ const count = derived(() =>
93
+ Object.values(lines.value).reduce((a, b) => a + b, 0),
94
+ )
95
+ const add = (id: string) => lines.set(d => {
96
+ d[id] = (d[id] ?? 0) + 1
97
+ })
98
+ return { lines, count, add }
99
+ }, { history: { limit: 100 } })
100
+ ```
101
+
102
+ Read it as `cart.count.value` and call `cart.add('p1')`. The handle also has `$name`, `$reset()` (every box back to
103
+ its initial value), `$snapshot()` (a plain copy) and, with `history`, `$history`: `undo()`, `redo()`, `clear()`,
104
+ `canUndo`, `canRedo` and `entries`.
105
+
106
+ `state` options inside a setup:
107
+
108
+ | Option | Does |
109
+ |---|---|
110
+ | `persist: 'local' \| 'session' \| 'cookie' \| 'memory'` | Keeps the box through reloads. The short form takes a primitive `init` only |
111
+ | `persist: { in, schema, version, migrate, maxAge }` | Objects and arrays need a Standard Schema (Zod, Valibot, ArkType). `migrate` maps old versions; `maxAge` is for cookies, in seconds |
112
+ | `sync: 'tabs'` | The same value in every tab. Needs `persist`, and not `'session'` |
113
+ | `history: false` | Leaves the box out of undo |
114
+ | `name` | The box's name in its scope. A persisted box the setup doesn't return needs one |
115
+
116
+ Misuse throws a `StateError` in dev with a code and a fix: S008 (persistence or sync set up wrongly), S009 (two
117
+ scopes with one name, a reserved `$` key, or `$history` without `history`). `kerf check` reports S001 (server data
118
+ copied into `state`) and S012 (`state.linked` over a query with no `key`). On the server, a scope is per request:
119
+ reaching one outside a render is S002, and reading a `local` or `session` box there shows `init` (S013).
120
+
121
+ In tests, `scope(cart)` from `@kerf-js/core/test` makes a fresh instance with no UI, and `render(App, props, { state,
122
+ storage })` seeds scopes and shares storage between renders: `kerf docs testing`.
package/docs/style.md ADDED
@@ -0,0 +1,82 @@
1
+ # Styling: style groups
2
+
3
+ Style with **groups** from `@kerf-js/core/style`, not class lists. A group is a named thing (`order-card`), its variations
4
+ (axes), its pieces (parts) and its states, all written in tokens. The markup says what an element is and which
5
+ variation it's in: `<article data-g="order-card" data-status="late">`.
6
+
7
+ ```tsx
8
+ import { group } from '@kerf-js/core/style'
9
+
10
+ /** A summary card for one order in a list. */
11
+ export const orderCard = group('order-card', {
12
+ base: {
13
+ surface: 'raised',
14
+ pad: 'group',
15
+ radius: 'surface',
16
+ layout: 'stack',
17
+ gap: 'related',
18
+ },
19
+ axes: {
20
+ status: {
21
+ open: { tone: 'info' },
22
+ shipped: { tone: 'positive' },
23
+ late: { tone: 'critical' },
24
+ },
25
+ },
26
+ parts: {
27
+ title: { text: 'title' },
28
+ meta: { text: 'caption', ink: 'subtle' },
29
+ },
30
+ states: { selected: { ring: 'accent' } },
31
+ defaults: { status: 'open' },
32
+ })
33
+
34
+ type Order = {
35
+ name: string
36
+ date: string
37
+ status: 'open' | 'shipped' | 'late'
38
+ }
39
+
40
+ export function OrderCard(props: {
41
+ order: Order
42
+ selected: boolean
43
+ }) {
44
+ const { order, selected } = props
45
+ return (
46
+ <article {...orderCard({ status: order.status, selected })}>
47
+ <h3 {...orderCard.title}>{order.name}</h3>
48
+ <p {...orderCard.meta}>{order.date}</p>
49
+ </article>
50
+ )
51
+ }
52
+ ```
53
+
54
+ ## Rules
55
+
56
+ 1. **Find before you write.** `kerf style find card` (MCP `style_find`) lists the groups that fit. Reuse one, or
57
+ add an axis value to it. A second group for the same thing is D021.
58
+ 2. **Values are tokens.** Each key is an intent (`surface pad gap radius tone emphasis text ink layout align justify
59
+ ring …`) and each value one of its tokens. `pad: '13px'` is a type error and D025. Raw CSS goes in
60
+ `css: { … }`, which is counted (D023): use it only where no intent sets the property.
61
+ 3. **Variation is an axis value**, set from state: `orderCard({ status: order.status })`. A reactive axis is one
62
+ attribute write; no class string is rebuilt.
63
+ 4. **A one-off is an accent**: `orderCard({ status: 'late', accent: { radius: 'round' } })`. Tokens only. The same
64
+ accent three times means it's an axis value (D022). An accent that sets what the site's axis value sets is D024.
65
+ 5. **One group per element** (D024). For a second look, nest an element or make it an axis.
66
+ 6. **States are ARIA or data attributes** (`selected` → `aria-selected`), and `hover`/`focus`/`active`/`disabled`
67
+ are read from the element, not passed.
68
+ 7. **No class soup.** More than 8 classes on an element, or the same class list in two places, is D020.
69
+
70
+ ## Tools
71
+
72
+ - `kerf style find <query>`: groups that fit, best first, with axes, parts, states and how often each is used.
73
+ - `kerf style explain order-card --status late` (or `order-card[status=late]`, `order-card.title`, or a DOM selector
74
+ copied from devtools): every declaration on the root and parts, in cascade order, with the token, axis, state,
75
+ compound or accent it came from, and the CSS that variation emits. MCP `style_explain`.
76
+ - `.kerf/styles.json`: the generated matrix (every group's axes, values, parts, accents, resolved CSS, uses and
77
+ `similar` groups). `kerf dev`/`build` and `kerf check` keep it current; `kerf style matrix` writes it. Read it;
78
+ never edit it.
79
+
80
+ Codes: D020 class soup, D021 near-duplicate groups, D022 a repeated accent, D023 the `css` escape, D024 styles that
81
+ fight (two groups on one element, overlapping compounds, an accent against an axis), D025 an unknown name, W060 a
82
+ group that isn't literal data.
@@ -0,0 +1,158 @@
1
+ # Surfaces (`@kerf-js/core/surface`)
2
+
3
+ A canvas or WebGL view that sits in layout like any other child. `setup` runs once on the client, props are live, and
4
+ nothing around it re-renders. Never write a raw `<canvas>`.
5
+
6
+ ```tsx
7
+ import { state } from '@kerf-js/core'
8
+ import { defineSurface, Surface } from '@kerf-js/core/surface'
9
+ import { z } from 'zod'
10
+
11
+ export const Bars = defineSurface({
12
+ name: 'bars',
13
+ kind: 'canvas2d', // or 'webgl2'
14
+ // Or defineSurface<{ data: number[] }, 'canvas2d'>({ ... })
15
+ props: z.object({ data: z.array(z.number()) }),
16
+ // Runs once; props.data is live, so never destructure it.
17
+ setup(s, props) {
18
+ // Repaints on box changes; the canvas is cleared first.
19
+ s.draw(() => {
20
+ const { width, height } = s.size.value // CSS px, live
21
+ // Live theme colours: .css, or .linear for shaders.
22
+ s.ctx.fillStyle = s.tokens.accent.css
23
+ props.data.forEach((v, i) => {
24
+ s.ctx.fillRect(i * 12, height - v, 10, v)
25
+ })
26
+ })
27
+ },
28
+ })
29
+
30
+ export function Page() {
31
+ const rows = state([3, 7, 5])
32
+ return (
33
+ <Surface
34
+ use={Bars}
35
+ data={rows.value}
36
+ aspect="16/9"
37
+ label="Sales by month"
38
+ />
39
+ )
40
+ }
41
+ ```
42
+
43
+ A control beside the surface needs only a box and a live prop. Nothing re-renders when it moves:
44
+
45
+ ```tsx
46
+ import { state } from '@kerf-js/core'
47
+ import { defineSurface, Surface } from '@kerf-js/core/surface'
48
+
49
+ // Name the kind too, so s.ctx is typed.
50
+ export const Stars = defineSurface<{ density: number }, 'canvas2d'>({
51
+ name: 'stars',
52
+ kind: 'canvas2d',
53
+ setup(s, props) {
54
+ // Every tick; reading props.density here keeps it live.
55
+ s.frame(({ seconds }) => {
56
+ for (let i = 0; i < props.density; i++) {
57
+ const { width, height } = s.size.value
58
+ const x = (i * 37 + seconds * 20) % width
59
+ const y = (i * 91) % height
60
+ s.ctx.fillRect(x, y, 1, 1)
61
+ }
62
+ })
63
+ },
64
+ })
65
+
66
+ export function Sky() {
67
+ const density = state(100)
68
+ const setDensity = (e: Event & {
69
+ currentTarget: HTMLInputElement
70
+ }) => (density.value = e.currentTarget.valueAsNumber)
71
+ return <>
72
+ <input
73
+ type="range"
74
+ min="10"
75
+ max="500"
76
+ value={density.value}
77
+ onInput={setDensity}
78
+ aria-label="Density"
79
+ />
80
+ <Surface
81
+ use={Stars}
82
+ density={density.value}
83
+ aspect="16/9"
84
+ decorative
85
+ />
86
+ </>
87
+ }
88
+ ```
89
+
90
+ **`<Surface>`:** `use`, your props, `aspect` (default `2/1`), `label` (required, X009) or `decorative`, `class`, `style`.
91
+ The server renders a sized placeholder, so nothing shifts when the canvas mounts. Put pointer handlers on `s.el`.
92
+
93
+ **`s`:**
94
+ - `s.ctx` (`canvas2d`), `s.gl` (`webgl2`), `s.canvas`, `s.el`
95
+ - `s.size`, `s.dpr`, `s.scale`: boxes. `canvas2d` draws in CSS px; `webgl2` has its viewport set for you
96
+ - `s.tokens.accent`: `--accent`, else `--veneer-accent`, as `{ css, linear }`
97
+ - `s.draw(fn)`: paint when a box it read changes
98
+ - `s.frame(t => ...)`: animate: `t.frame`, `t.seconds`, `t.delta`. Also repaints on a box change while paused
99
+ - `s.invalidate()`: book a paint by hand
100
+ - `s.text(text, options)`: text; see below
101
+ - `return () => ...` from `setup` to clean up
102
+
103
+ `defineSurface` also takes `fps` (default 60), `maxDpr` (default 2), `clear: false`, `context` (`getContext` attributes),
104
+ and `pixel: { width, height }` for a fixed target with integer scale and nearest sampling. `maxDpr` may be a `State`:
105
+ a page that governs its frame rate writes it, and the canvas refits without waiting for a resize.
106
+
107
+ **The clock** is shared: `import { clock } from '@kerf-js/core/surface'`, then `clock.pause()`, `clock.play()`, `clock.seek(seconds)`.
108
+ `seek` paints every animated surface now, so a capture is deterministic. Under `prefers-reduced-motion: reduce` it
109
+ starts paused on the first frame. Off-screen surfaces skip their paints.
110
+
111
+ ## Text
112
+
113
+ Never `fillText` (X010). `s.text()` keeps a real element over the text, so selection, find, translation, screen readers,
114
+ forced colours and print all work:
115
+
116
+ ```tsx
117
+ const score = s.text(() => `Score ${props.score}`, {
118
+ x: 8, y: 8, width: 200,
119
+ font: '600 16px Inter', lineHeight: 22,
120
+ })
121
+ ```
122
+
123
+ - Options may be a function, for live positions: `() => ({ x: s.size.value.width / 2, ... })`.
124
+ - `font` and `lineHeight` default to the CSS on the mirror. `color` defaults to the surface's. `align` is `left`,
125
+ `center` or `right`. Name a family (X002).
126
+ - It returns `{ el, lineCount, height }`; the last two are boxes.
127
+ - Canvas `s.text()` needs the `text.measure` slot, so add `text()` from `@kerf-js/text` to `plugins` in
128
+ kerf.config.ts (P101). Its engine loads lazily. On `webgl2` the mirror is the visible text, and no plugin is needed.
129
+ - `s.decorative(() => ctx.fillText(...))` is for text that is truly decoration.
130
+
131
+ ## Testing
132
+
133
+ jsdom has no canvas, so `@kerf-js/core/test` gives it a recording one:
134
+
135
+ <!-- example: skip imports the Page above from its own file -->
136
+ ```tsx
137
+ import {
138
+ canvasCalls,
139
+ clock,
140
+ fakeMeasure,
141
+ flush,
142
+ render,
143
+ } from '@kerf-js/core/test'
144
+ import { expect, test } from 'vitest'
145
+ import { Page } from './Page' // the Bars page above
146
+
147
+ test('draws a bar per value', async () => {
148
+ clock.install()
149
+ render(Page, {}, { slots: { 'text.measure': fakeMeasure() } })
150
+ await flush()
151
+ await clock.advance(16) // a frame
152
+ const canvas = document.querySelector('canvas')!
153
+ const bars = canvasCalls(canvas).filter(c => c.name === 'fillRect')
154
+ expect(bars).toHaveLength(3)
155
+ })
156
+ ```
157
+
158
+ `kerf surfaces --json` (MCP `surfaces`) lists what the project already has.
@@ -0,0 +1,81 @@
1
+ # Testing (`@kerf-js/core/test`, vitest)
2
+
3
+ A new app has no test runner. Add one:
4
+
5
+ ```bash
6
+ npm install -D vitest jsdom @testing-library/dom \
7
+ @testing-library/user-event
8
+ ```
9
+
10
+ <!-- example: skip @kerf-js/core/vite has no type declarations yet (TS7016 under strict) -->
11
+ ```ts
12
+ // vitest.config.ts
13
+ import kerf from '@kerf-js/core/vite'
14
+ import { defineConfig } from 'vitest/config'
15
+
16
+ export default defineConfig({
17
+ plugins: [kerf()],
18
+ test: { environment: 'jsdom' },
19
+ })
20
+ ```
21
+
22
+ Then `npx vitest run`. A test:
23
+
24
+ ```tsx
25
+ import { state } from '@kerf-js/core'
26
+ import { render, screen, user } from '@kerf-js/core/test'
27
+ import { expect, test } from 'vitest'
28
+
29
+ function Cart() {
30
+ const count = state(0)
31
+ return (
32
+ <button type="button" onClick={() => count.value++}>
33
+ Cart ({count.value})
34
+ </button>
35
+ )
36
+ }
37
+
38
+ test('adding to the cart', async () => {
39
+ render(Cart)
40
+ await user.click(screen.getByRole('button', { name: 'Cart (0)' }))
41
+ expect(screen.getByRole('button', { name: 'Cart (1)' }))
42
+ .toBeTruthy()
43
+ const click = () => user.click(screen.getByRole('button'))
44
+ await expect(click).toTouchAtMost(1, { runs: 2 })
45
+ })
46
+ ```
47
+
48
+ - `render(Component, props, options)` mounts into the document with a fresh app; unmounted after each test.
49
+ `options.state` seeds `defineState` scopes, `options.storage` (`memoryStorage()`) is shared between renders to play
50
+ two tabs or a reload, and `options.slots` binds plugin slots. `scope(handle)` runs one scope with no UI.
51
+ - `flush()` applies pending updates. Every `user` action and `clock.advance` already ends in one.
52
+ - `screen` has role, label and text queries only (`getByRole`, `getByLabelText`, `getByText`, with `getAll`/`query`/`find`).
53
+ - `user.click`, `dblClick`, `type`, `clear`, `keyboard`, `hover`, `unhover`, `tab`, `selectOptions`, `deselectOptions`,
54
+ `upload` and `paste` (`@testing-library/user-event`) each end in `flush()`: never sleep or `waitFor`.
55
+ - `clock.install()` before the code schedules timers, then `await clock.advance(ms)` (or `clock.runAll()`): drives
56
+ timers, rAF, `Date` and the resources that wait on them, and flushes. Uninstalled after each test.
57
+ - `touches(fn)` returns `{ mutations, runs, … }` for one interaction. `toTouchAtMost(n, { runs })` bounds both: DOM writes
58
+ alone miss identity bugs that re-run every row but write the DOM once (W014).
59
+
60
+ ## Junk tests: T001–T009
61
+
62
+ `kerf check` reports these on test files (`test.include` in the config). A test that finishes without an assertion
63
+ also fails at runtime (T001). T012 and T013 are about open listeners and real sockets: `kerf docs browser` and
64
+ `kerf docs start`; T010, T011 and T020 are the gate: `kerf docs verify`.
65
+
66
+ | Code | Catches | Instead |
67
+ |---|---|---|
68
+ | T001 | No assertion, or `expect(x)` with no matcher | Assert what the user sees |
69
+ | T002 | `expect(true).toBe(true)`, `expect(x).toBe(x)` | Assert on the code's output |
70
+ | T003 | `n.value = 5; expect(n.value).toBe(5)` | Act through the UI, assert what depends on it |
71
+ | T004 | `setTimeout` sleeps, real timers, `waitFor` | `flush()`, `clock.advance(ms)` |
72
+ | T005 | `container`, selectors, classes, `innerHTML`, test ids, app state in a component test (warning) | Role, label, text |
73
+ | T006 | `vi.mock('@kerf-js/core')`, mocking the component under test | Fake the edges (API, storage) |
74
+ | T007 | Snapshots | Behavior assertions |
75
+ | T008 | `expect` under `if`/`?:`/`&&`/`catch`, or only inside loops | Assert the condition, then assert unconditionally |
76
+ | T009 | `.only`, `.skip`, `fit`, `xit` | Remove it; `test.fails` for a test meant to fail |
77
+
78
+ A deliberate exception needs a reason: `// kerf-allow T007: the exported SVG is the product`. In the file's header
79
+ comments it covers the whole file; elsewhere, its own line and the next.
80
+
81
+ Plugins can use this clock too: `fakePay` from `@kerf-js/pay/test` plays a rail on it, through your real webhook and ledger. `kerf docs pay`.